mirror of
https://github.com/Unleash/unleash.git
synced 2025-09-28 17:55:15 +02:00
This PR refactors the `NetworkTrafficUsage.tsx` and `useTrafficData` files a bit. The primary objective was to make the network traffic usage component easier to work with, so I suggest to the reviewer that they start there. Part of that refactoring, was taking things out of the useTraffic hook that didn't need to be there. In the end, I'd removed so much that I didn't even need the hook itself in the new component, so I switched that to a regular useState. It made more sense to me to put some of the functions inside the hook into a separate file and import them directly (because they don't rely on any hook state), so I have done that and removed those functions from the trafficData hook. In this case, I also moved the tests. I have not added any new tests in this PR, but will do so in a follow-up. The functions I intend to test have been marked as such.
79 lines
1.8 KiB
TypeScript
79 lines
1.8 KiB
TypeScript
import useSWR from 'swr';
|
|
import { useMemo } from 'react';
|
|
import { formatApiPath } from 'utils/formatPath';
|
|
import handleErrorResponses from '../httpErrorResponseHandler';
|
|
import type {
|
|
TrafficUsageDataSegmentedCombinedSchema,
|
|
TrafficUsageDataSegmentedSchema,
|
|
} from 'openapi';
|
|
|
|
export interface IInstanceTrafficMetricsResponse {
|
|
usage: TrafficUsageDataSegmentedSchema;
|
|
|
|
refetch: () => void;
|
|
|
|
loading: boolean;
|
|
|
|
error?: Error;
|
|
}
|
|
|
|
export const useInstanceTrafficMetrics = (
|
|
period: string,
|
|
): IInstanceTrafficMetricsResponse => {
|
|
const { data, error, mutate } = useSWR(
|
|
formatApiPath(`api/admin/metrics/traffic/${period}`),
|
|
fetcher,
|
|
);
|
|
|
|
return useMemo(
|
|
() => ({
|
|
usage: data,
|
|
loading: !error && !data,
|
|
refetch: () => mutate(),
|
|
error,
|
|
}),
|
|
[data, error, mutate],
|
|
);
|
|
};
|
|
|
|
export type InstanceTrafficMetricsResponse2 = {
|
|
usage: TrafficUsageDataSegmentedCombinedSchema;
|
|
|
|
refetch: () => void;
|
|
|
|
loading: boolean;
|
|
|
|
error?: Error;
|
|
};
|
|
|
|
export const useInstanceTrafficMetrics2 = (
|
|
grouping: 'monthly' | 'daily',
|
|
{
|
|
from,
|
|
to,
|
|
}: {
|
|
from: string;
|
|
to: string;
|
|
},
|
|
): InstanceTrafficMetricsResponse2 => {
|
|
const apiPath = `api/admin/metrics/traffic-search?grouping=${grouping}&from=${from}&to=${to}`;
|
|
|
|
const { data, error, mutate } = useSWR(formatApiPath(apiPath), fetcher);
|
|
|
|
return useMemo(
|
|
() => ({
|
|
usage: data,
|
|
loading: !error && !data,
|
|
refetch: () => mutate(),
|
|
error,
|
|
}),
|
|
[data, error, mutate],
|
|
);
|
|
};
|
|
|
|
const fetcher = (path: string) => {
|
|
return fetch(path)
|
|
.then(handleErrorResponses('Instance Metrics'))
|
|
.then((res) => res.json());
|
|
};
|