demarches-normaliennes/app/javascript/components/shared/queryCache.js

53 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-10-07 17:41:20 +02:00
import { QueryCache } from 'react-query';
import { isNumeric } from '@utils';
2020-11-25 15:17:59 +01:00
import matchSorter from 'match-sorter';
2020-10-07 17:41:20 +02:00
const { api_geo_url, api_adresse_url } = gon.autocomplete || {};
export const queryCache = new QueryCache({
defaultConfig: {
queries: {
queryFn: defaultQueryFn
}
}
});
function buildURL(scope, term) {
if (scope === 'adresse') {
return `${api_adresse_url}/search?q=${term}&limit=5`;
} else if (isNumeric(term)) {
const code = term.padStart(2, '0');
return `${api_geo_url}/${scope}?code=${code}&limit=5`;
}
return `${api_geo_url}/${scope}?nom=${term}&limit=5`;
}
function buildOptions() {
if (window.AbortController) {
const controller = new AbortController();
const signal = controller.signal;
return [{ signal }, controller];
}
return [{}, null];
}
async function defaultQueryFn(scope, term) {
2020-11-25 15:17:59 +01:00
if (scope == 'pays') {
2020-11-30 10:53:55 +01:00
return matchSorter(await getPays(), term, { keys: ['nom'] });
2020-11-25 15:17:59 +01:00
}
2020-10-07 17:41:20 +02:00
const url = buildURL(scope, term);
const [options, controller] = buildOptions();
const promise = fetch(url, options).then((response) => response.json());
promise.cancel = () => controller && controller.abort();
return promise;
}
2020-11-30 10:53:55 +01:00
let paysCache;
async function getPays() {
if (!paysCache) {
paysCache = await fetch('/pays.json').then((response) => response.json());
}
return paysCache;
}