1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-02-14 00:19:16 +01:00
unleash.unleash/frontend/src/hooks/api/getters/useFeature/useFeature.ts
Nuno Góis 4167a60588
feat: biome lint frontend (#4903)
Follows up on https://github.com/Unleash/unleash/pull/4853 to add Biome
to the frontend as well.


![image](https://github.com/Unleash/unleash/assets/14320932/1906faf1-fc29-4172-a4d4-b2716d72cd65)

Added a few `biome-ignore` to speed up the process but we may want to
check and fix them in the future.
2023-10-02 13:25:46 +01:00

74 lines
1.7 KiB
TypeScript

import useSWR, { SWRConfiguration } from 'swr';
import { useCallback } from 'react';
import { emptyFeature } from './emptyFeature';
import handleErrorResponses from '../httpErrorResponseHandler';
import { formatApiPath } from 'utils/formatPath';
import { IFeatureToggle } from 'interfaces/featureToggle';
export interface IUseFeatureOutput {
feature: IFeatureToggle;
refetchFeature: () => void;
loading: boolean;
status?: number;
error?: Error;
}
export interface IFeatureResponse {
status: number;
body?: IFeatureToggle;
}
export const useFeature = (
projectId: string,
featureId: string,
options?: SWRConfiguration,
): IUseFeatureOutput => {
const path = formatFeatureApiPath(projectId, featureId);
const { data, error, mutate } = useSWR<IFeatureResponse>(
['useFeature', path],
() => featureFetcher(path),
options,
);
const refetchFeature = useCallback(() => {
mutate().catch(console.warn);
}, [mutate]);
return {
feature: data?.body || emptyFeature,
refetchFeature,
loading: !error && !data,
status: data?.status,
error,
};
};
export const featureFetcher = 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(),
};
};
export const formatFeatureApiPath = (
projectId: string,
featureId: string,
): string => {
return formatApiPath(
`api/admin/projects/${projectId}/features/${featureId}?variantEnvironments=true`,
);
};