Files
supabase/apps/studio/data/open-api/api-spec-query.ts

70 lines
1.9 KiB
TypeScript

import { useQuery } from '@tanstack/react-query'
import { openApiKeys } from './keys'
import { get, handleError } from '@/data/fetchers'
import type { ResponseError, UseCustomQueryOptions } from '@/types'
export type OpenAPISpecVariables = {
projectRef?: string
}
export type OpenAPISpecResponse = {
data: any
tables: any[]
functions: any[]
}
export async function getOpenAPISpec({ projectRef }: OpenAPISpecVariables, signal?: AbortSignal) {
if (!projectRef) throw new Error('projectRef is required')
const { data, error } = await get(`/platform/projects/{ref}/api/rest`, {
params: { path: { ref: projectRef } },
signal,
})
if (error) handleError(error)
const definitions = (data as any).definitions
const tables = definitions
? Object.entries(definitions).map(([key, table]: any) => ({
...table,
name: key,
fields: Object.entries(table.properties || {}).map(([key, field]: any) => ({
...field,
name: key,
})),
}))
: []
const paths = (data as any).paths
const functions = paths
? Object.entries(paths)
.map(([path, value]: any) => ({
...value,
path,
name: path.replace('/rpc/', ''),
}))
.filter((x) => x.path.includes('/rpc'))
.sort((a, b) => a.name.localeCompare(b.name))
: []
return { data: data, tables, functions }
}
export type OpenAPISpecData = Awaited<OpenAPISpecResponse>
export type OpenAPISpecError = ResponseError
export const useOpenAPISpecQuery = <TData = OpenAPISpecData>(
{ projectRef }: OpenAPISpecVariables,
{
enabled = true,
...options
}: UseCustomQueryOptions<OpenAPISpecData, OpenAPISpecError, TData> = {}
) =>
useQuery<OpenAPISpecData, OpenAPISpecError, TData>({
queryKey: openApiKeys.apiSpec(projectRef),
queryFn: ({ signal }) => getOpenAPISpec({ projectRef }, signal),
enabled: enabled && typeof projectRef !== 'undefined',
...options,
})