demarches-normaliennes/app/javascript/components/shared/queryClient.ts

63 lines
1.6 KiB
TypeScript
Raw Normal View History

import { QueryClient, QueryFunction } from 'react-query';
2023-03-21 14:40:33 +01:00
import { httpRequest, getConfig } from '@utils';
2020-10-07 17:41:20 +02:00
const API_EDUCATION_QUERY_LIMIT = 5;
const API_ADRESSE_QUERY_LIMIT = 5;
const {
2023-03-21 14:40:33 +01:00
autocomplete: { api_adresse_url, api_education_url }
} = getConfig();
2020-10-07 17:41:20 +02:00
type QueryKey = readonly [
scope: string,
term: string,
extra: string | undefined
];
2020-10-07 17:41:20 +02:00
2023-03-21 14:40:33 +01:00
function buildURL(scope: string, term: string) {
term = term.replace(/\(|\)/g, '');
const params = new URLSearchParams();
2023-03-21 14:40:33 +01:00
let path = '';
if (scope == 'adresse') {
path = `${api_adresse_url}/search`;
params.set('q', term);
params.set('limit', `${API_ADRESSE_QUERY_LIMIT}`);
} else if (scope == 'annuaire-education') {
path = `${api_education_url}/search`;
params.set('q', term);
params.set('rows', `${API_EDUCATION_QUERY_LIMIT}`);
params.set('dataset', 'fr-en-annuaire-education');
2020-10-07 17:41:20 +02:00
}
return `${path}?${params}`;
2020-10-07 17:41:20 +02:00
}
const defaultQueryFn: QueryFunction<unknown, QueryKey> = async ({
2023-03-21 14:40:33 +01:00
queryKey: [scope, term],
signal
}) => {
// BAN will error with queries less then 3 chars long
if (scope == 'adresse' && term.length < 3) {
return {
type: 'FeatureCollection',
version: 'draft',
features: [],
query: term
};
}
2023-03-21 14:40:33 +01:00
const url = buildURL(scope, term);
return httpRequest(url, { csrf: false, signal }).json();
};
2020-11-30 10:53:55 +01:00
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
// we don't really care about global queryFn type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
queryFn: defaultQueryFn as any
}
}
});