useIsSchemaExposed.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { useMemo } from 'react'
  2. import {
  3. parseDbSchemaString,
  4. useProjectPostgrestConfigQuery,
  5. } from '@/data/config/project-postgrest-config-query'
  6. type UseIsSchemaExposedParams = {
  7. projectRef?: string
  8. schemaName?: string
  9. }
  10. type UseIsSchemaExposedOptions = {
  11. enabled?: boolean
  12. }
  13. export type UseIsSchemaExposedReturn =
  14. | {
  15. status: 'pending'
  16. data: undefined
  17. isPending: true
  18. isError: false
  19. isSuccess: false
  20. }
  21. | {
  22. status: 'error'
  23. data: undefined
  24. isPending: false
  25. isError: true
  26. isSuccess: false
  27. }
  28. | {
  29. status: 'success'
  30. data: boolean
  31. isPending: false
  32. isError: false
  33. isSuccess: true
  34. }
  35. export const useIsSchemaExposed = (
  36. { projectRef, schemaName }: UseIsSchemaExposedParams,
  37. { enabled = true }: UseIsSchemaExposedOptions = {}
  38. ): UseIsSchemaExposedReturn => {
  39. const shouldQueryConfig = enabled && !!projectRef && !!schemaName
  40. const {
  41. data: dbSchemaString,
  42. isPending: isConfigPending,
  43. isError: isConfigError,
  44. } = useProjectPostgrestConfigQuery(
  45. { projectRef },
  46. { enabled: shouldQueryConfig, select: ({ db_schema }) => db_schema }
  47. )
  48. const exposedSchemas = useMemo(() => {
  49. if (!dbSchemaString) return []
  50. return parseDbSchemaString(dbSchemaString)
  51. }, [dbSchemaString])
  52. if (!shouldQueryConfig || isConfigPending) {
  53. return { status: 'pending', data: undefined, isPending: true, isError: false, isSuccess: false }
  54. }
  55. if (isConfigError) {
  56. return { status: 'error', data: undefined, isPending: false, isError: true, isSuccess: false }
  57. }
  58. return {
  59. status: 'success',
  60. data: exposedSchemas.includes(schemaName),
  61. isPending: false,
  62. isError: false,
  63. isSuccess: true,
  64. }
  65. }