UNPKG

@ideal-postcodes/address-finder

Version:

Address Finder JS library backed by the Ideal Postcodes UK address search API

75 lines (74 loc) 2.06 kB
import { autocomplete } from "@ideal-postcodes/core-axios"; /** * @hidden */ export class ApiCache { constructor(client) { this.prefix = "!"; this.client = client; this.cache = {}; } key(query) { return `${this.prefix}${query.toLowerCase()}`; } retrieve(query) { return this.cache[this.key(query)]; } store(query, data) { this.cache[this.key(query)] = data; return data; } clear() { this.cache = {}; } /** * Retrieve a list of address suggestions given a query * * Write and read from cache if previously requested */ query(query, options = {}) { const cachedValue = this.retrieve(query); if (cachedValue) return Promise.resolve(cachedValue); const p = autocomplete .list(this.client, { query: { query, api_key: this.client.config.api_key, ...options, }, }) .then((response) => { const suggestions = response.body.result.hits; this.store(query, suggestions); return suggestions; }); this.store(query, p); return p; } resolve(suggestion, format, options = {}) { if (format === "usa") return this.usaResolve(suggestion, options); return this.gbrResolve(suggestion, options); } usaResolve(suggestion, options = {}) { return autocomplete .usa(this.client, suggestion.id, { query: { api_key: this.client.config.api_key, ...options, }, }) .then((response) => response.body.result); } gbrResolve(suggestion, options = {}) { return autocomplete .gbr(this.client, suggestion.id, { query: { api_key: this.client.config.api_key, ...options, }, }) .then((response) => response.body.result); } }