2021-09-14 14:20:23 +02:00
|
|
|
import useSWR, { mutate } from 'swr';
|
|
|
|
import { useState, useEffect } from 'react';
|
|
|
|
|
|
|
|
import { formatApiPath } from '../../../../utils/format-path';
|
|
|
|
import { IFeatureToggle } from '../../../../interfaces/featureToggle';
|
|
|
|
import { defaultFeature } from './defaultFeature';
|
|
|
|
|
2021-09-27 13:35:32 +02:00
|
|
|
interface IUseFeatureOptions {
|
|
|
|
refreshInterval?: number;
|
|
|
|
revalidateOnFocus?: boolean;
|
|
|
|
revalidateOnReconnect?: boolean;
|
|
|
|
revalidateIfStale?: boolean;
|
|
|
|
}
|
|
|
|
|
|
|
|
const useFeature = (
|
|
|
|
projectId: string,
|
|
|
|
id: string,
|
2021-10-01 13:49:18 +02:00
|
|
|
options: IUseFeatureOptions = {}
|
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-07 23:04:14 +02:00
|
|
|
|
|
|
|
const res = await fetch(path, {
|
2021-09-14 14:20:23 +02:00
|
|
|
method: 'GET',
|
2021-10-07 23:04:14 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
// If the status code is not in the range 200-299,
|
|
|
|
// we still try to parse and throw it.
|
|
|
|
if (!res.ok) {
|
|
|
|
const error = new Error('An error occurred while fetching the data.')
|
|
|
|
// Attach extra info to the error object.
|
|
|
|
// @ts-ignore
|
|
|
|
error.info = await res.json();
|
|
|
|
// @ts-ignore
|
|
|
|
error.status = res.status;
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
|
|
|
|
return 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;
|