77 lines
2.4 KiB
JavaScript
77 lines
2.4 KiB
JavaScript
"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 {
|
|
constructor(db) {
|
|
this.log = (0, log_1.createLog)('geocode');
|
|
this.baseUrl = 'https://geocode.maps.co/search';
|
|
this.apiKey = (0, env_1.envString)('GEOCODE_API_KEY', null);
|
|
this.db = db;
|
|
}
|
|
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;
|
|
}
|
|
if (response.status !== 200) {
|
|
this.log.warn(`Invalid response from API [${response.status}]`);
|
|
return null;
|
|
}
|
|
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
|