Skip to content

Instantly share code, notes, and snippets.

@cblanc
Created December 28, 2020 05:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cblanc/db3c3143a7485a5287ce63dd6656557e to your computer and use it in GitHub Desktop.
Save cblanc/db3c3143a7485a5287ce63dd6656557e to your computer and use it in GitHub Desktop.
Autocomplete Cache
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