57 lines
1.6 KiB
JavaScript
57 lines
1.6 KiB
JavaScript
const axios = require('axios');
|
|
|
|
const BASE_URL = "https://www.xeno-canto.org/api/2/recordings?query=";
|
|
|
|
function getCoords({ coords }) {
|
|
if (!!coords) {
|
|
if (!!coords.lat && !!coords.lon) {
|
|
return `lat:${coords.lat} lon:${coords.lon}`;
|
|
} else if (!!coords.box) {
|
|
/** TODO box coordinates*/
|
|
}
|
|
}
|
|
}
|
|
|
|
function search(query) {
|
|
let url;
|
|
if (typeof (query) === 'string') {
|
|
url = BASE_URL + query;
|
|
} else if (typeof (query) === 'object') {
|
|
const xeno_params = [
|
|
{ name: "" },
|
|
{ genus: 'gen:' },
|
|
{ recordist: 'rec:' },
|
|
{ country: 'cnt:' },
|
|
{ location: 'loc:' },
|
|
{ remarks: 'rmk:' },
|
|
{ coords: getCoords(query) },
|
|
{ also: 'also:' },
|
|
{ type: 'type:' },
|
|
{ nr: 'nr:' },
|
|
{ quality: 'q:' },
|
|
{ qualitylt: 'q<:' },
|
|
{ area: 'area:' }
|
|
];
|
|
let url_params = xeno_params.reduce(function (acc, param) {
|
|
const key = Object.keys(param)[0];
|
|
if (!!query[key]) {
|
|
if (key === 'coords') {
|
|
acc += param[key] + " ";
|
|
} else {
|
|
acc += param[key] + query[key] + " ";
|
|
}
|
|
};
|
|
return acc;
|
|
}, "");
|
|
url = BASE_URL + url_params;
|
|
} else {
|
|
throw new Error("Null query error");
|
|
}
|
|
return axios.get(url).then(response => {
|
|
return response.data;
|
|
}).catch(error => {
|
|
throw error;
|
|
});
|
|
}
|
|
|
|
module.exports = { search }; |