2021-10-20 12:05:44 +02:00
|
|
|
import useSWR, { mutate, SWRConfiguration } from 'swr';
|
2022-03-09 14:59:24 +01:00
|
|
|
import { useCallback } from 'react';
|
|
|
|
import { emptyFeature } from './emptyFeature';
|
2021-10-15 09:21:38 +02:00
|
|
|
import handleErrorResponses from '../httpErrorResponseHandler';
|
2022-03-10 10:52:50 +01:00
|
|
|
import { formatApiPath } from 'utils/format-path';
|
|
|
|
import { IFeatureToggle } from 'interfaces/featureToggle';
|
2021-09-14 14:20:23 +02:00
|
|
|
|
2022-03-09 14:59:24 +01:00
|
|
|
interface IUseFeatureOutput {
|
|
|
|
feature: IFeatureToggle;
|
|
|
|
refetchFeature: () => void;
|
|
|
|
loading: boolean;
|
2022-03-10 10:52:50 +01:00
|
|
|
status?: number;
|
2022-03-09 14:59:24 +01:00
|
|
|
error?: Error;
|
|
|
|
}
|
2021-09-14 14:20:23 +02:00
|
|
|
|
2022-03-10 10:52:50 +01:00
|
|
|
interface IFeatureResponse {
|
|
|
|
status: number;
|
|
|
|
body?: IFeatureToggle;
|
|
|
|
}
|
|
|
|
|
2022-03-09 14:59:24 +01:00
|
|
|
export const useFeature = (
|
|
|
|
projectId: string,
|
|
|
|
featureId: string,
|
|
|
|
options?: SWRConfiguration
|
|
|
|
): IUseFeatureOutput => {
|
|
|
|
const path = formatApiPath(
|
|
|
|
`api/admin/projects/${projectId}/features/${featureId}`
|
|
|
|
);
|
|
|
|
|
2022-03-10 10:52:50 +01:00
|
|
|
const { data, error } = useSWR<IFeatureResponse>(
|
2022-03-09 14:59:24 +01:00
|
|
|
path,
|
|
|
|
() => fetcher(path),
|
|
|
|
options
|
|
|
|
);
|
|
|
|
|
|
|
|
const refetchFeature = useCallback(() => {
|
|
|
|
mutate(path).catch(console.warn);
|
|
|
|
}, [path]);
|
2021-09-14 14:20:23 +02:00
|
|
|
|
|
|
|
return {
|
2022-03-10 10:52:50 +01:00
|
|
|
feature: data?.body || emptyFeature,
|
2022-03-09 14:59:24 +01:00
|
|
|
refetchFeature,
|
|
|
|
loading: !error && !data,
|
2022-03-10 10:52:50 +01:00
|
|
|
status: data?.status,
|
2021-09-14 14:20:23 +02:00
|
|
|
error,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
2022-03-10 10:52:50 +01:00
|
|
|
const fetcher = async (path: string): Promise<IFeatureResponse> => {
|
|
|
|
const res = await fetch(path);
|
|
|
|
|
|
|
|
if (res.status === 404) {
|
|
|
|
return { status: 404 };
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!res.ok) {
|
|
|
|
await handleErrorResponses('Feature toggle data')(res);
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
status: res.status,
|
|
|
|
body: await res.json(),
|
|
|
|
};
|
2022-03-09 14:59:24 +01:00
|
|
|
};
|