The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
move api docs to react-query
Alaister Younga2bb6df2a580
diff --git a/studio/data/docs/keys.ts b/studio/data/docs/keys.tsnew file mode 100644index 00000000000..b0f66362945--- /dev/null+++ b/studio/data/docs/keys.ts@@ -0,0 +1,7 @@+export const docsKeys = {+ jsonSchema: (+ projectRef: string | undefined,+ swaggerUrl: string | undefined,+ apiKey: string | undefined+ ) => ['projects', projectRef, 'docs', { swaggerUrl, apiKey }] as const,+}diff --git a/studio/data/docs/project-json-schema-query.ts b/studio/data/docs/project-json-schema-query.tsnew file mode 100644index 00000000000..f37f6dd55cb--- /dev/null+++ b/studio/data/docs/project-json-schema-query.ts@@ -0,0 +1,75 @@+import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'+import { get } from 'lib/common/fetch'+import { useCallback } from 'react'+import { docsKeys } from './keys'++export type ProjectJsonSchemaVariables = {+ projectRef?: string+ swaggerUrl?: string+ apiKey?: string+}++export type ProjectJsonSchemaResponse = any++export async function getProjectJsonSchema(+ { projectRef, swaggerUrl, apiKey }: ProjectJsonSchemaVariables,+ signal?: AbortSignal+) {+ if (!projectRef) {+ throw new Error('projectRef is required')+ }+ if (!swaggerUrl) {+ throw new Error('id is required')+ }++ let headers: {+ [key: string]: string | undefined+ } = { apikey: apiKey }+ if ((apiKey?.length ?? 0) > 40) headers['Authorization'] = `Bearer ${apiKey}`++ const response = await get(swaggerUrl, {+ signal,+ headers,+ credentials: 'omit',+ })+ if (response.error) {+ throw response.error+ }++ return response as ProjectJsonSchemaResponse+}++export type ProjectJsonSchemaData = Awaited<ReturnType<typeof getProjectJsonSchema>>+export type ProjectJsonSchemaError = unknown++export const useProjectJsonSchemaQuery = <TData = ProjectJsonSchemaData>(+ { projectRef, swaggerUrl, apiKey }: ProjectJsonSchemaVariables,+ {+ enabled = true,+ ...options+ }: UseQueryOptions<ProjectJsonSchemaData, ProjectJsonSchemaError, TData> = {}+) =>+ useQuery<ProjectJsonSchemaData, ProjectJsonSchemaError, TData>(+ docsKeys.jsonSchema(projectRef, swaggerUrl, apiKey),+ ({ signal }) => getProjectJsonSchema({ projectRef, swaggerUrl, apiKey }, signal),+ {+ enabled: enabled && typeof projectRef !== 'undefined' && typeof swaggerUrl !== 'undefined',+ ...options,+ }+ )++export const useProjectJsonSchemaPrefetch = ({+ projectRef,+ swaggerUrl,+ apiKey,+}: ProjectJsonSchemaVariables) => {+ const client = useQueryClient()++ return useCallback(() => {+ if (projectRef && swaggerUrl) {+ client.prefetchQuery(docsKeys.jsonSchema(projectRef, swaggerUrl, apiKey), ({ signal }) =>+ getProjectJsonSchema({ projectRef, swaggerUrl, apiKey }, signal)+ )+ }+ }, [projectRef, swaggerUrl])+}diff --git a/studio/pages/project/[ref]/api/index.tsx b/studio/pages/project/[ref]/api/index.tsxindex 482494908ff..2cee443f4dc 100644--- a/studio/pages/project/[ref]/api/index.tsx+++ b/studio/pages/project/[ref]/api/index.tsx@@ -1,18 +1,18 @@-import useSWR, { mutate } from 'swr'import { useRouter } from 'next/router'import { Button, Dropdown, IconKey } from 'ui'import { FC, createContext, useContext, useEffect, useState } from 'react'import { observer, useLocalObservable } from 'mobx-react-lite'import { NextPageWithLayout } from 'types'-import { API_URL, IS_PLATFORM } from 'lib/constants'+import { IS_PLATFORM } from 'lib/constants'import { PROJECT_ENDPOINT_PROTOCOL } from 'pages/api/constants'-import { checkPermissions, useStore } from 'hooks'-import { get } from 'lib/common/fetch'+import { checkPermissions, useParams, useStore } from 'hooks'import { snakeToCamel } from 'lib/helpers'+import { useProjectApiQuery } from 'data/config/project-api-query'import { DocsLayout } from 'components/layouts'import { GeneralContent, ResourceContent, RpcContent } from 'components/interfaces/Docs'import { PermissionAction } from '@supabase/shared-types/out/constants'+import { useProjectJsonSchemaQuery } from 'data/docs/project-json-schema-query'const PageContext = createContext(null)@@ -67,35 +67,38 @@ const DEFAULT_KEY = { name: 'hide', key: 'SUPABASE_KEY' }const DocView: FC<any> = observer(({}) => {const PageState: any = useContext(PageContext)- const router = useRouter()+ const { ref: projectRef, page, resource, rpc } = useParams()const [selectedLang, setSelectedLang] = useState<any>('js')const [showApiKey, setShowApiKey] = useState<any>(DEFAULT_KEY)- const { data, error }: any = useSWR(`${API_URL}/props/project/${PageState.projectRef}/api`, get)- const API_KEY = data?.autoApiService?.defaultApiKey+ const { data, error } = useProjectApiQuery({+ projectRef,+ })++ const apiKey = data?.autoApiService?.defaultApiKeyconst swaggerUrl = data?.autoApiService?.restUrl- const headers: any = { apikey: API_KEY }const canReadServiceKey = checkPermissions(PermissionAction.READ,'service_api_keys.service_role_key')- if (API_KEY?.length > 40) headers['Authorization'] = `Bearer ${API_KEY}`-- const { data: jsonSchema, error: jsonSchemaError } = useSWR(- () => swaggerUrl,- (url: string) => get(url, { headers, credentials: 'omit' }).then((res) => res)- )+ const {+ data: jsonSchema,+ error: jsonSchemaError,+ refetch,+ } = useProjectJsonSchemaQuery({+ projectRef,+ swaggerUrl,+ apiKey,+ })useEffect(() => {PageState.setJsonSchema(jsonSchema)}, [jsonSchema])const refreshDocs = async () => {- // A bit hacky calling coding this up twice - at some point we should move this function- // and the SWR into the store.- mutate(swaggerUrl)+ await refetch()}if (error || jsonSchemaError)@@ -122,8 +125,6 @@ const DocView: FC<any> = observer(({}) => {: `${PROJECT_ENDPOINT_PROTOCOL}://${data.autoApiService.endpoint}`,}- const { query } = router- const { page, resource, rpc } = queryconst { paths, definitions } = PageState.jsonSchemaconst PAGE_KEY: any = resource || rpc || page || 'index'