Skip to content

Instantly share code, notes, and snippets.

@cblanc
Created Dec 28, 2020
Embed
What would you like to do?
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