Created
December 28, 2020 05:59
-
-
Save cblanc/db3c3143a7485a5287ce63dd6656557e to your computer and use it in GitHub Desktop.
Autocomplete Cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Client } from "@ideal-postcodes/core-browser"; | |
import { AddressSuggestion, Address } from "@ideal-postcodes/api-typings"; | |
export class ApiCache { | |
private client: Client; | |
private cache: Record<string, AddressSuggestion[]>; | |
private prefix = "!"; | |
constructor(client: Client) { | |
this.client = client; | |
this.cache = {}; | |
} | |
key(query: string): string { | |
return `${this.prefix}${query.toLowerCase()}`; | |
} | |
retrieve(query: string): AddressSuggestion[] | undefined { | |
return this.cache[this.key(query)]; | |
} | |
store(query: string, data: AddressSuggestion[]) { | |
this.cache[this.key(query)] = data; | |
} | |
clear() { | |
this.cache = {}; | |
} | |
/** | |
* Retrieve a list of address suggestions given a query | |
* | |
* Write and read from cache if previously requested | |
*/ | |
query(query: string): Promise<AddressSuggestion[]> { | |
const cachedValue = this.retrieve(query); | |
if (cachedValue) return Promise.resolve(cachedValue); | |
return this.client.autocomplete | |
.list({ query: { query, api_key: this.client.api_key } }) | |
.then((response) => { | |
const suggestions = response.body.result.hits; | |
this.store(query, suggestions); | |
return suggestions; | |
}); | |
} | |
resolve(suggestion: AddressSuggestion): Promise<Address | null> { | |
const { umprn, udprn } = suggestion; | |
if (umprn !== undefined) return this.client.lookupUmprn({ umprn }); | |
return this.client.lookupUdprn({ udprn }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment