soundbirder/controllers/region.js

46 lines
1.4 KiB
JavaScript
Executable File

require('dotenv').config();
const debug = require('debug')('soundbirder:api:region');
const cache = require('./cache');
const axios = require('axios');
const OPENCAGE_API_KEY = process.env.OPENCAGE_API_KEY;
const OPENCAGE_API_URL = 'https://api.opencagedata.com/geocode/v1/json?q=<lat>+<lon>&key=<key>';
async function getRegion(lat, lon) {
const url = OPENCAGE_API_URL
.replace('<lat>', lat)
.replace('<lon>', lon)
.replace('<key>', OPENCAGE_API_KEY);
try {
const cached = await cache.getCached(`region-${lat}-${lon}`);
if (cached) {
return cached;
}
} catch (error) {
throw error;
}
return axios.get(url).then(response => {
const { results } = response.data;
const region = results[0].components;
region.country_code = region.country_code.toUpperCase();
cache.cacheResponse(url, region);
return { country_code, country, state, county } = region;
}).catch(error => {
throw error;
});
}
function getRegionCode({ country_code, country, state, county }) {
return eBird.ref.region.list('subnational1', country_code)()
.then(states => {
console.log(states);
const regionCode = states.find(region => region.name === state).code;
return regionCode;
}).catch(error => {
throw error;
});
}
module.exports = {
getRegion,
}