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';
|
2021-09-14 14:20:23 +02:00
|
|
|
import { IFeatureToggle } from '../../../../interfaces/featureToggle';
|
2022-03-09 14:59:24 +01:00
|
|
|
import { emptyFeature } from './emptyFeature';
|
2021-10-15 09:21:38 +02:00
|
|
|
import handleErrorResponses from '../httpErrorResponseHandler';
|
2022-03-09 14:59:24 +01:00
|
|
|
import { formatApiPath } from '../../../../utils/format-path';
|
2021-09-14 14:20:23 +02:00
|
|
|
|
2022-03-09 14:59:24 +01:00
|
|
|
interface IUseFeatureOutput {
|
|
|
|
feature: IFeatureToggle;
|
|
|
|
featureCacheKey: string;
|
|
|
|
refetchFeature: () => void;
|
|
|
|
loading: boolean;
|
|
|
|
error?: Error;
|
|
|
|
}
|
2021-09-14 14:20:23 +02:00
|
|
|
|
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}`
|
|
|
|
);
|
|
|
|
|
|
|
|
const { data, error } = useSWR<IFeatureToggle>(
|
|
|
|
path,
|
|
|
|
() => fetcher(path),
|
|
|
|
options
|
|
|
|
);
|
|
|
|
|
|
|
|
const refetchFeature = useCallback(() => {
|
|
|
|
mutate(path).catch(console.warn);
|
|
|
|
}, [path]);
|
2021-09-14 14:20:23 +02:00
|
|
|
|
|
|
|
return {
|
2022-03-09 14:59:24 +01:00
|
|
|
feature: data || emptyFeature,
|
|
|
|
featureCacheKey: path,
|
|
|
|
refetchFeature,
|
|
|
|
loading: !error && !data,
|
2021-09-14 14:20:23 +02:00
|
|
|
error,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
2022-03-09 14:59:24 +01:00
|
|
|
const fetcher = async (path: string) => {
|
|
|
|
return fetch(path)
|
|
|
|
.then(handleErrorResponses('Feature toggle data'))
|
|
|
|
.then(res => res.json());
|
|
|
|
};
|