Browse Source

CLDC-4066: Implement a debounce on address search

disappointingly the underlying library https://github.com/alphagov/accessible-autocomplete doesn't have this as an option, though we can implement one ourselves in the fetch code
CLDC-4066-improve-resilience-to-os-places-api-outage
Samuel Young 3 days ago
parent
commit
7ab95ba211
  1. 18
      app/frontend/controllers/address_search_controller.js

18
app/frontend/controllers/address_search_controller.js

@ -4,10 +4,28 @@ import 'accessible-autocomplete/dist/accessible-autocomplete.min.css'
const options = [] const options = []
let latestQueryId = 0;
const sleep = (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
}
const fetchOptions = async (query, searchUrl) => { const fetchOptions = async (query, searchUrl) => {
if (query.length < 2) { if (query.length < 2) {
throw new Error('Query must be at least 2 characters long.') throw new Error('Query must be at least 2 characters long.')
} }
// implement a debounce
// this is because this API has periods of high latency if OS Places has an outage
// making too many requests can overwhelm the number of threads available on the server
// which can in turn cause a site wide outage
latestQueryId++;
const myQueryId = latestQueryId;
await sleep(500);
if (myQueryId !== latestQueryId) {
throw new Error('Outdated query, ignoring result.');
}
try { try {
const response = await fetch(`${searchUrl}?query=${encodeURIComponent(query.trim())}`) const response = await fetch(`${searchUrl}?query=${encodeURIComponent(query.trim())}`)
return await response.json() return await response.json()

Loading…
Cancel
Save