useSingleLog.tsx 2.1 KB

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