traxxx/src/utils/resolve-place.js

46 lines
1.2 KiB
JavaScript
Raw Normal View History

'use strict';
2020-05-15 02:40:59 +00:00
const logger = require('../logger')(__filename);
const http = require('./http');
async function resolvePlace(query) {
if (!query) {
return null;
}
2020-05-15 02:40:59 +00:00
try {
// https://operations.osmfoundation.org/policies/nominatim/
const res = await http.get(`https://nominatim.openstreetmap.org/search/${encodeURI(query)}?format=json&accept-language=en&addressdetails=1`, {
'User-Agent': 'contact at moonloop.adult@protonmail.com',
}, { queueMethod: '1s' });
2020-05-15 02:40:59 +00:00
const [item] = res.body;
2020-05-15 02:40:59 +00:00
if (item && item.address) {
const rawPlace = item.address;
const place = {};
if (item.class === 'place' || item.class === 'boundary') {
const location = rawPlace[item.type] || rawPlace.city || rawPlace.place;
if (location) {
place.place = location;
place.city = rawPlace.city || location;
}
}
2020-05-15 02:40:59 +00:00
if (rawPlace.state) place.state = rawPlace.state;
if (rawPlace.country_code) place.country = rawPlace.country_code.toUpperCase();
if (rawPlace.continent) place.continent = rawPlace.continent;
return place;
}
} catch (error) {
logger.error(`Failed to resolve place '${query}': ${error.message}`);
}
return null;
}
module.exports = resolvePlace;