Updated OSM API path, added redis caching.

This commit is contained in:
DebaucheryLibrarian
2023-08-02 23:12:41 +02:00
parent 0500bdee2b
commit c5d81e94e5
6 changed files with 201 additions and 2 deletions

View File

@@ -5,12 +5,26 @@ const config = require('config');
const knex = require('../knex');
const logger = require('../logger')(__filename);
const http = require('./http');
const slugify = require('./slugify');
const argv = require('../argv');
const redis = require('../redis');
async function resolvePlace(query) {
if (!query) {
return null;
}
const cacheKey = `place-${slugify(query)}`;
const cachedPlace = await redis.hGetAll(cacheKey);
if (cachedPlace && argv.placeCache !== false) {
await redis.expire(cacheKey, 3600 * 24 * 30);
logger.debug(`Using cached place '${cacheKey}' for query '${query}': ${JSON.stringify(cachedPlace)}`);
return cachedPlace;
}
// query is a nationality, lookup would get weird results (British resolves to British, Northern Ireland)
const country = await knex('countries')
.where('nationality', 'ilike', `%${query}%`)
@@ -27,7 +41,7 @@ async function resolvePlace(query) {
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`, {
const res = await http.get(`https://nominatim.openstreetmap.org/search?q=${encodeURI(query)}&format=json&accept-language=en&addressdetails=1`, {
headers: {
'User-Agent': config.location.userAgent,
},
@@ -54,6 +68,11 @@ async function resolvePlace(query) {
if (rawPlace.country_code) place.country = rawPlace.country_code.toUpperCase();
if (rawPlace.continent) place.continent = rawPlace.continent;
logger.debug(`Resolved place '${query}' to ${JSON.stringify(place)}`);
await redis.hSet(cacheKey, place);
await redis.expire(cacheKey, 3600 * 24 * 30);
return place;
}
} catch (error) {