59 lines
1.9 KiB
TypeScript
59 lines
1.9 KiB
TypeScript
import { useQuery } from "@tanstack/react-query";
|
|
import type { StatisticsRequest, ProductResponse, BannerResponse } from "@/types/lg";
|
|
import {fetchBannerStatistics, fetchProductStatistics} from "@/lib/lg-dashboard";
|
|
|
|
const sortRecord = <T,>(obj?: Record<string, T> | null): Record<string, T> => {
|
|
if (!obj) return {};
|
|
return Object.fromEntries(
|
|
Object.keys(obj)
|
|
.sort()
|
|
.map((k) => [k, obj[k]])
|
|
);
|
|
};
|
|
|
|
const sortNumberArrayRecord = (obj?: Record<string, number[]> | null): Record<string, number[]> => {
|
|
if (!obj) return {};
|
|
return Object.fromEntries(
|
|
Object.keys(obj)
|
|
.sort()
|
|
.map((k) => [k, [...(obj[k] ?? [])].sort((a, b) => a - b)])
|
|
);
|
|
};
|
|
|
|
// queryKey에 넣을 “안정적인 req”
|
|
const normalizeReqForKey = (req: StatisticsRequest) => ({
|
|
variableIdMap: sortRecord(req.variableIdMap),
|
|
bannerIdList: [...(req.bannerIdList ?? [])].sort(),
|
|
filterCondition: sortNumberArrayRecord(req.filterCondition as any), // normalizeFilterCondition 결과면 Record<string, number[]>
|
|
option: req.option ?? null,
|
|
});
|
|
|
|
export const productStatisticsKey = (req: StatisticsRequest) =>
|
|
["statistics", "product", normalizeReqForKey(req)] as const;
|
|
|
|
export const bannerStatisticsKey = (req: StatisticsRequest) =>
|
|
["statistics", "banner", normalizeReqForKey(req)] as const;
|
|
|
|
export function useProductStatisticsQuery(req: StatisticsRequest, enabled = true) {
|
|
return useQuery<ProductResponse>({
|
|
queryKey: productStatisticsKey(req),
|
|
queryFn: () => fetchProductStatistics(req),
|
|
enabled,
|
|
staleTime: 60_000,
|
|
gcTime: 10 * 60_000,
|
|
});
|
|
}
|
|
|
|
export function useBannerStatisticsQuery(req: StatisticsRequest, enabled = true) {
|
|
return useQuery<BannerResponse>({
|
|
queryKey: bannerStatisticsKey(req),
|
|
queryFn: () => fetchBannerStatistics(req),
|
|
enabled,
|
|
/*
|
|
refetchOnMount: "always",
|
|
staleTime: 0,
|
|
*/
|
|
staleTime: 60_000,
|
|
gcTime: 10 * 60_000,
|
|
});
|
|
} |