photosite/dist/geocode/index.js

77 lines
2.4 KiB
JavaScript
Raw Normal View History

2024-12-09 20:15:27 +00:00
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Geocode = void 0;
require("dotenv/config");
const url_1 = require("url");
const node_fetch_1 = __importDefault(require("node-fetch"));
const log_1 = require("../log");
const env_1 = require("../env");
class Geocode {
2024-12-11 02:38:41 +00:00
constructor(db) {
2024-12-09 20:15:27 +00:00
this.log = (0, log_1.createLog)('geocode');
this.baseUrl = 'https://geocode.maps.co/search';
this.apiKey = (0, env_1.envString)('GEOCODE_API_KEY', null);
2024-12-11 02:38:41 +00:00
this.db = db;
2024-12-09 20:15:27 +00:00
}
async query(location) {
let res = await this.db.getLocation(location);
if (res === null) {
res = await this.api(location);
}
return res;
}
toLatLng(obj) {
return {
latitude: parseFloat(obj.lat),
longitude: parseFloat(obj.lon)
};
}
//https://geocode.maps.co/search?q=&api_key=675738aa38619885468998kehbf6458
async api(location) {
const url = new url_1.URL(this.baseUrl);
let response;
let json;
let res = null;
url.searchParams.append('q', location);
this.log.info(`Querying API: ${url.href}`);
url.searchParams.append('api_key', this.apiKey);
await this.delay(1000); //rate limit to 1/sec
try {
response = await (0, node_fetch_1.default)(url.href);
}
catch (err) {
this.log.error('Error getting response', err);
return null;
}
2024-12-11 02:38:41 +00:00
if (response.status !== 200) {
this.log.warn(`Invalid response from API [${response.status}]`);
return null;
}
2024-12-09 20:15:27 +00:00
try {
json = await response.json();
}
catch (err) {
this.log.error('Error parsing json', err);
return null;
}
if (json.length < 1) {
return null;
}
res = this.toLatLng(json[0]);
await this.db.cacheLocation(location, res);
return res;
}
async delay(ms) {
return new Promise((resolve, reject) => {
return setTimeout(resolve, ms);
});
}
cache(location, latitude, longitude) {
}
}
exports.Geocode = Geocode;
module.exports = { Geocode };
//# sourceMappingURL=index.js.map