2022-02-08 12:49:51 +01:00
|
|
|
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
|
|
|
|
2021-07-20 12:41:16 +02:00
|
|
|
const API_EDUCATION_QUERY_LIMIT = 5;
|
|
|
|
const API_ADRESSE_QUERY_LIMIT = 5;
|
|
|
|
|
2022-07-07 11:39:03 +02:00
|
|
|
const {
|
2023-03-21 14:40:33 +01:00
|
|
|
autocomplete: { api_adresse_url, api_education_url }
|
2022-07-07 11:39:03 +02:00
|
|
|
} = getConfig();
|
2020-10-07 17:41:20 +02:00
|
|
|
|
2022-02-08 12:49:51 +01: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) {
|
2023-02-27 12:01:12 +01:00
|
|
|
term = term.replace(/\(|\)/g, '');
|
2023-02-22 17:22:00 +01:00
|
|
|
const params = new URLSearchParams();
|
2023-03-21 14:40:33 +01:00
|
|
|
let path = '';
|
2023-02-22 17:22:00 +01:00
|
|
|
|
|
|
|
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
|
|
|
}
|
2023-02-22 17:22:00 +01:00
|
|
|
|
|
|
|
return `${path}?${params}`;
|
2020-10-07 17:41:20 +02:00
|
|
|
}
|
|
|
|
|
2022-02-08 12:49:51 +01:00
|
|
|
const defaultQueryFn: QueryFunction<unknown, QueryKey> = async ({
|
2023-03-21 14:40:33 +01:00
|
|
|
queryKey: [scope, term],
|
2022-04-28 23:19:03 +02:00
|
|
|
signal
|
2022-02-08 12:49:51 +01:00
|
|
|
}) => {
|
2023-02-27 12:01:12 +01:00
|
|
|
// BAN will error with queries less then 3 chars long
|
|
|
|
if (scope == 'adresse' && term.length < 3) {
|
2023-02-27 18:41:02 +01:00
|
|
|
return {
|
|
|
|
type: 'FeatureCollection',
|
|
|
|
version: 'draft',
|
|
|
|
features: [],
|
|
|
|
query: term
|
|
|
|
};
|
2023-02-27 12:01:12 +01:00
|
|
|
}
|
|
|
|
|
2023-03-21 14:40:33 +01:00
|
|
|
const url = buildURL(scope, term);
|
2022-04-28 23:19:03 +02:00
|
|
|
return httpRequest(url, { csrf: false, signal }).json();
|
2022-02-08 12:49:51 +01:00
|
|
|
};
|
2020-11-30 10:53:55 +01:00
|
|
|
|
2022-02-08 12:49:51 +01:00
|
|
|
export const queryClient = new QueryClient({
|
|
|
|
defaultOptions: {
|
|
|
|
queries: {
|
2022-02-23 13:27:07 +01:00
|
|
|
// we don't really care about global queryFn type
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
2022-02-08 12:49:51 +01:00
|
|
|
queryFn: defaultQueryFn as any
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|