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 { GeoCoordinates } from "../../types";
import { CodedError, ErrorCode } from "../../errors";
export abstract class Geocoder {
@@ -39,11 +40,26 @@ export abstract class Geocoder {
*/
public async getLocation( location: string ): Promise<GeoCoordinates> {
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 );
this.cache.set( location, coords );
return coords;
try {
const coords: GeoCoordinates = await this.geocodeLocation( location );
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;
}
}
}