2021-10-20 12:05:44 +02:00
|
|
|
import useSWR, { mutate, SWRConfiguration } from 'swr';
|
2021-09-14 14:20:23 +02:00
|
|
|
import { useState, useEffect } from 'react';
|
|
|
|
|
|
|
|
import { formatApiPath } from '../../../../utils/format-path';
|
|
|
|
import { IFeatureToggle } from '../../../../interfaces/featureToggle';
|
|
|
|
import { defaultFeature } from './defaultFeature';
|
2021-10-15 09:21:38 +02:00
|
|
|
import handleErrorResponses from '../httpErrorResponseHandler';
|
2021-09-14 14:20:23 +02:00
|
|
|
|
2021-09-27 13:35:32 +02:00
|
|
|
const useFeature = (
|
|
|
|
projectId: string,
|
|
|
|
id: string,
|
2021-10-20 12:05:44 +02:00
|
|
|
options: SWRConfiguration = {}
|
2021-09-27 13:35:32 +02:00
|
|
|
) => {
|
2021-10-07 23:04:14 +02:00
|
|
|
const fetcher = async () => {
|
2021-09-14 14:20:23 +02:00
|
|
|
const path = formatApiPath(
|
|
|
|
`api/admin/projects/${projectId}/features/${id}`
|
|
|
|
);
|
2021-10-15 09:21:38 +02:00
|
|
|
return fetch(path, {
|
2021-09-14 14:20:23 +02:00
|
|
|
method: 'GET',
|
2021-10-20 12:05:44 +02:00
|
|
|
})
|
|
|
|
.then(handleErrorResponses('Feature toggle data'))
|
|
|
|
.then(res => res.json());
|
2021-09-14 14:20:23 +02:00
|
|
|
};
|
|
|
|
|
2021-09-27 13:35:32 +02:00
|
|
|
const FEATURE_CACHE_KEY = `api/admin/projects/${projectId}/features/${id}`;
|
|
|
|
|
|
|
|
const { data, error } = useSWR<IFeatureToggle>(FEATURE_CACHE_KEY, fetcher, {
|
|
|
|
...options,
|
|
|
|
});
|
2021-09-14 14:20:23 +02:00
|
|
|
|
|
|
|
const [loading, setLoading] = useState(!error && !data);
|
|
|
|
|
|
|
|
const refetch = () => {
|
2021-09-27 13:35:32 +02:00
|
|
|
mutate(FEATURE_CACHE_KEY);
|
2021-09-14 14:20:23 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
setLoading(!error && !data);
|
|
|
|
}, [data, error]);
|
|
|
|
|
|
|
|
return {
|
2021-09-27 13:35:32 +02:00
|
|
|
feature: data || defaultFeature,
|
2021-09-14 14:20:23 +02:00
|
|
|
error,
|
|
|
|
loading,
|
|
|
|
refetch,
|
2021-09-27 13:35:32 +02:00
|
|
|
FEATURE_CACHE_KEY,
|
2021-09-14 14:20:23 +02:00
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
export default useFeature;
|