Cache invalid locations

This commit is contained in:
Matthew Oslan
2020-07-11 00:32:36 -04:00
parent 91968dc1be
commit 252a68fd8e
2 changed files with 20 additions and 5 deletions

View File

@@ -1,6 +1,7 @@
import fs = require("fs"); import fs = require("fs");
import { GeoCoordinates } from "../../types"; import { GeoCoordinates } from "../../types";
import { CodedError, ErrorCode } from "../../errors";
export abstract class Geocoder { export abstract class Geocoder {
@@ -39,11 +40,26 @@ export abstract class Geocoder {
*/ */
public async getLocation( location: string ): Promise<GeoCoordinates> { public async getLocation( location: string ): Promise<GeoCoordinates> {
if ( this.cache.has( location ) ) { if ( this.cache.has( location ) ) {
return this.cache.get( location ); const coords: GeoCoordinates = this.cache.get( location );
if ( coords == null ) {
// Throw an error if there are no results for this location.
throw new CodedError( ErrorCode.NoLocationFound );
} else {
return coords;
}
} }
const coords: GeoCoordinates = await this.geocodeLocation( location ); try {
this.cache.set( location, coords ); const coords: GeoCoordinates = await this.geocodeLocation( location );
return coords; this.cache.set( location, coords );
return coords;
} catch ( ex ) {
if ( ex instanceof CodedError && ex.errCode == ErrorCode.NoLocationFound ) {
// Store in the cache the fact that this location has no results.
this.cache.set( location, null );
}
throw ex;
}
} }
} }

View File

@@ -27,7 +27,6 @@ export default class GoogleMaps extends Geocoder {
} }
if ( !data.results.length ) { if ( !data.results.length ) {
console.log( `No results found for location "${ location }"` );
throw new CodedError( ErrorCode.NoLocationFound ); throw new CodedError( ErrorCode.NoLocationFound );
} }