2022-03-28 02:39:42 -05:00
|
|
|
import { ArbitraryObject, RequestErrorBody } from '@logto/schemas';
|
2022-03-24 02:02:31 -05:00
|
|
|
import { HTTPError } from 'ky';
|
2022-03-16 02:34:03 -05:00
|
|
|
import { useCallback } from 'react';
|
2022-03-28 02:39:42 -05:00
|
|
|
import { useTranslation } from 'react-i18next';
|
2022-03-16 02:34:03 -05:00
|
|
|
import { BareFetcher } from 'swr';
|
|
|
|
|
|
|
|
import useApi, { RequestError } from './use-api';
|
|
|
|
|
|
|
|
const useSwrFetcher = () => {
|
2022-03-24 02:02:31 -05:00
|
|
|
const api = useApi({ hideErrorToast: true });
|
2022-03-28 02:39:42 -05:00
|
|
|
const { t } = useTranslation();
|
2022-03-16 02:34:03 -05:00
|
|
|
const fetcher = useCallback<BareFetcher>(
|
|
|
|
async (resource, init) => {
|
2022-03-24 02:02:31 -05:00
|
|
|
try {
|
|
|
|
const response = await api.get(resource, init);
|
2022-03-28 02:39:42 -05:00
|
|
|
const data = await response.json<ArbitraryObject>();
|
2022-03-16 02:34:03 -05:00
|
|
|
|
2022-03-28 02:39:42 -05:00
|
|
|
if (typeof resource === 'string' && resource.includes('?')) {
|
|
|
|
const parameters = new URLSearchParams(resource.split('?')[1]);
|
|
|
|
|
|
|
|
if (parameters.get('page') && parameters.get('page_size')) {
|
|
|
|
const number = response.headers.get('Total-Number');
|
|
|
|
|
|
|
|
if (!number) {
|
|
|
|
throw new Error(t('admin_console.errors.missing_total_number'));
|
|
|
|
}
|
|
|
|
|
|
|
|
return [data, Number(number)];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return data;
|
2022-03-24 02:02:31 -05:00
|
|
|
} catch (error: unknown) {
|
|
|
|
if (error instanceof HTTPError) {
|
|
|
|
const { response } = error;
|
2022-03-21 22:15:24 -05:00
|
|
|
const metadata = await response.json<RequestErrorBody>();
|
2022-03-24 02:02:31 -05:00
|
|
|
throw new RequestError(metadata);
|
|
|
|
}
|
|
|
|
throw error;
|
2022-03-16 02:34:03 -05:00
|
|
|
}
|
|
|
|
},
|
2022-03-28 02:39:42 -05:00
|
|
|
[api, t]
|
2022-03-16 02:34:03 -05:00
|
|
|
);
|
|
|
|
|
|
|
|
return fetcher;
|
|
|
|
};
|
|
|
|
|
|
|
|
export default useSwrFetcher;
|