useSingleLog.tsx82 lines · main
| 1 | import { useQuery } from '@tanstack/react-query' |
| 2 | |
| 3 | import { LOGS_TABLES } from '@/components/interfaces/Settings/Logs/Logs.constants' |
| 4 | import type { |
| 5 | LogData, |
| 6 | Logs, |
| 7 | LogsEndpointParams, |
| 8 | QueryType, |
| 9 | } from '@/components/interfaces/Settings/Logs/Logs.types' |
| 10 | import { genSingleLogQuery } from '@/components/interfaces/Settings/Logs/Logs.utils' |
| 11 | import { get } from '@/data/fetchers' |
| 12 | import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled' |
| 13 | |
| 14 | interface SingleLogHook { |
| 15 | data: LogData | undefined |
| 16 | error: string | Object | null |
| 17 | isLoading: boolean |
| 18 | refresh: () => void |
| 19 | } |
| 20 | |
| 21 | type SingleLogParams = { |
| 22 | id?: string |
| 23 | projectRef: string |
| 24 | queryType?: QueryType |
| 25 | paramsToMerge?: Partial<LogsEndpointParams> |
| 26 | } |
| 27 | function useSingleLog({ |
| 28 | projectRef, |
| 29 | id, |
| 30 | queryType, |
| 31 | paramsToMerge, |
| 32 | }: SingleLogParams): SingleLogHook { |
| 33 | const table = queryType ? LOGS_TABLES[queryType] : undefined |
| 34 | const sql = id && table ? genSingleLogQuery(table, id) : '' |
| 35 | |
| 36 | const params: LogsEndpointParams = { ...paramsToMerge, sql } |
| 37 | |
| 38 | const enabled = Boolean(id && table) |
| 39 | |
| 40 | const { logsMetadata } = useIsFeatureEnabled(['logs:metadata']) |
| 41 | |
| 42 | const { |
| 43 | data, |
| 44 | error: rcError, |
| 45 | isPending, |
| 46 | isRefetching, |
| 47 | refetch, |
| 48 | } = useQuery({ |
| 49 | queryKey: ['projects', projectRef, 'single-log', id, queryType], |
| 50 | queryFn: async ({ signal }) => { |
| 51 | const { data, error } = await get(`/platform/projects/{ref}/analytics/endpoints/logs.all`, { |
| 52 | params: { |
| 53 | path: { ref: projectRef }, |
| 54 | query: params, |
| 55 | }, |
| 56 | signal, |
| 57 | }) |
| 58 | if (error) { |
| 59 | throw error |
| 60 | } |
| 61 | |
| 62 | return data as unknown as Logs |
| 63 | }, |
| 64 | enabled, |
| 65 | refetchOnWindowFocus: false, |
| 66 | refetchOnMount: false, |
| 67 | refetchOnReconnect: false, |
| 68 | }) |
| 69 | |
| 70 | let error: null | string | object = rcError ? (rcError as any).message : null |
| 71 | const result = data?.result ? data.result[0] : undefined |
| 72 | |
| 73 | return { |
| 74 | data: !!result |
| 75 | ? { ...result, metadata: logsMetadata ? result?.metadata : undefined } |
| 76 | : undefined, |
| 77 | isLoading: (enabled && isPending) || isRefetching, |
| 78 | error, |
| 79 | refresh: () => refetch(), |
| 80 | } |
| 81 | } |
| 82 | export default useSingleLog |