Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

1.6 KB
Raw Blame
import { useQuery } from '@tanstack/react-query'

import { replicationKeys } from './keys'
import { checkReplicationFeatureFlagRetry } from './utils'
import { get, handleError } from '@/data/fetchers'
import type { ResponseError, UseCustomQueryOptions } from '@/types'

type ReplicationSourcesParams = { projectRef?: string }

async function fetchReplicationSources(
  { projectRef }: ReplicationSourcesParams,
  signal?: AbortSignal
) {
  if (!projectRef) throw new Error('projectRef is required')

  const { data, error } = await get('/platform/replication/{ref}/sources', {
    params: { path: { ref: projectRef } },
    signal,
  })
  if (error) {
    handleError(error)
  }

  return data
}

export type ReplicationSourcesData = Awaited<ReturnType<typeof fetchReplicationSources>>

export const useReplicationSourcesQuery = <TData = ReplicationSourcesData>(
  { projectRef }: ReplicationSourcesParams,
  {
    enabled = true,
    ...options
  }: UseCustomQueryOptions<ReplicationSourcesData, ResponseError, TData> = {}
) =>
  useQuery<ReplicationSourcesData, ResponseError, TData>({
    queryKey: replicationKeys.sources(projectRef),
    queryFn: ({ signal }) => fetchReplicationSources({ projectRef }, signal),
    enabled: enabled && typeof projectRef !== 'undefined',
    refetchOnMount: false,
    refetchOnWindowFocus: false,
    retry: checkReplicationFeatureFlagRetry,
    ...options,
  })

export const useReplicationSourceId = ({ projectRef }: { projectRef?: string }) => {
  const { data: sourcesData } = useReplicationSourcesQuery({ projectRef })
  return sourcesData?.sources.find((s) => s.name === projectRef)?.id
}