From 252a68fd8e05428aa8a66de62c053a87a3320317 Mon Sep 17 00:00:00 2001 From: Matthew Oslan Date: Sat, 11 Jul 2020 00:32:36 -0400 Subject: [PATCH] Cache invalid locations --- routes/geocoders/Geocoder.ts | 24 ++++++++++++++++++++---- routes/geocoders/GoogleMaps.ts | 1 - 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/routes/geocoders/Geocoder.ts b/routes/geocoders/Geocoder.ts index 80e5c6d..3498502 100644 --- a/routes/geocoders/Geocoder.ts +++ b/routes/geocoders/Geocoder.ts @@ -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 { 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; + } } } diff --git a/routes/geocoders/GoogleMaps.ts b/routes/geocoders/GoogleMaps.ts index d5cbe35..237ee86 100644 --- a/routes/geocoders/GoogleMaps.ts +++ b/routes/geocoders/GoogleMaps.ts @@ -27,7 +27,6 @@ export default class GoogleMaps extends Geocoder { } if ( !data.results.length ) { - console.log( `No results found for location "${ location }"` ); throw new CodedError( ErrorCode.NoLocationFound ); }