Add geocoder cache

This commit is contained in:
Matthew Oslan
2020-06-06 15:57:16 -04:00
parent 378955d00b
commit bb67c78163
3 changed files with 41 additions and 2 deletions

View File

@@ -1,11 +1,49 @@
import fs = require("fs");
import { GeoCoordinates } from "../../types";
export abstract class Geocoder {
private static cacheFile: string = __dirname + "/../../../geocoderCache.json";
private cache: Map<string, GeoCoordinates>;
public constructor() {
// Load the cache from disk.
if ( fs.existsSync( Geocoder.cacheFile ) ) {
this.cache = new Map( JSON.parse( fs.readFileSync( Geocoder.cacheFile, "utf-8" ) ) );
} else {
this.cache = new Map();
}
// Write the cache to disk every 5 minutes.
setInterval( () => {
this.saveCache();
}, 5 * 60 * 1000 );
}
private saveCache(): void {
fs.writeFileSync( Geocoder.cacheFile, JSON.stringify( Array.from( this.cache.entries() ) ) );
}
/**
* Converts a location name to geographic coordinates.
* @param location A location name.
* @return A Promise that will be resolved with the GeoCoordinates of the specified location, or rejected with a
* CodedError.
*/
public abstract geocodeLocation( location: string ): Promise<GeoCoordinates>;
protected abstract geocodeLocation( location: string ): Promise<GeoCoordinates>;
/**
* Converts a location name to geographic coordinates, first checking the cache and updating it if necessary.
*/
public async getLocation( location: string ): Promise<GeoCoordinates> {
if ( this.cache.has( location ) ) {
return this.cache.get( location );
}
const coords: GeoCoordinates = await this.geocodeLocation( location );
this.cache.set( location, coords );
return coords;
}
}

View File

@@ -57,7 +57,7 @@ export async function resolveCoordinates( location: string ): Promise< GeoCoordi
const split: string[] = location.split( "," );
return [ parseFloat( split[ 0 ] ), parseFloat( split[ 1 ] ) ];
} else {
return GEOCODER.geocodeLocation( location );
return GEOCODER.getLocation( location );
}
}