The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
move useProjectSettings to react-query
Alaister Youngd38c8dc1d5fd
diff --git a/studio/components/interfaces/Functions/TerminalInstructions.tsx b/studio/components/interfaces/Functions/TerminalInstructions.tsxindex 4bf07d8c62d..32d1176236b 100644--- a/studio/components/interfaces/Functions/TerminalInstructions.tsx+++ b/studio/components/interfaces/Functions/TerminalInstructions.tsx@@ -1,12 +1,12 @@-import { useRouter } from 'next/router'-import { Button, IconTerminal, IconMaximize2, IconMinimize2, IconBookOpen, IconCode } from 'ui'-import { useProjectSettings } from 'hooks'-import { useAccessTokens } from 'hooks/queries/useAccessTokens'-import { Commands } from './Functions.types'import CommandRender from 'components/interfaces/Functions/CommandRender'-import { FC, useState } from 'react'-import { useStore } from 'hooks'+import { useProjectApiQuery } from 'data/config/project-api-query'+import { useParams } from 'hooks'+import { useAccessTokens } from 'hooks/queries/useAccessTokens'import Link from 'next/link'+import { useRouter } from 'next/router'+import { FC, useState } from 'react'+import { Button, IconBookOpen, IconCode, IconMaximize2, IconMinimize2, IconTerminal } from 'ui'+import { Commands } from './Functions.types'interface Props {closable?: boolean@@ -14,21 +14,19 @@ interface Props {const TerminalInstructions: FC<Props> = ({ closable = false }) => {const router = useRouter()- const { ref } = router.query- const { ui } = useStore()+ const { ref: projectRef } = useParams()++ const [showInstructions, setShowInstructions] = useState(!closable)const { tokens } = useAccessTokens()- const { services } = useProjectSettings(ref as string | undefined)- const [showInstructions, setShowInstructions] = useState(!closable)+ const { data: settings } = useProjectApiQuery({+ projectRef,+ })- // Get the API service- const API_SERVICE_ID = 1- const apiService = (services ?? []).find((x: any) => x.app.id == API_SERVICE_ID)- const apiKeys = apiService?.service_api_keys ?? []- const anonKey = apiKeys.find((x: any) => x.name === 'anon key')?.api_key+ const anonKey = settings?.autoApiService.defaultApiKey+ const endpoint = settings?.autoApiService.app_config.endpoint ?? ''- const endpoint = apiService?.app_config.endpoint ?? ''const endpointSections = endpoint.split('.')const functionsEndpoint = [...endpointSections.slice(0, 1),@@ -37,8 +35,8 @@ const TerminalInstructions: FC<Props> = ({ closable = false }) => {].join('.')// get the .co or .net TLD from the restUrl- const restUrl = ui.selectedProject?.restUrl- const restUrlTld = new URL(restUrl as string).hostname.split('.').pop()+ const restUrl = settings?.autoApiService.restUrl ?? ''+ const restUrlTld = new URL(restUrl).hostname.split('.').pop()const commands: Commands[] = [{@@ -54,20 +52,20 @@ const TerminalInstructions: FC<Props> = ({ closable = false }) => {comment: 'Create a function',},{- command: `supabase functions deploy hello-world --project-ref ${ref}`,+ command: `supabase functions deploy hello-world --project-ref ${projectRef}`,description: 'Deploys function at ./functions/hello-world/index.ts',jsx: () => {return (<><span className="text-brand-1100">supabase</span> functions deploy hello-world- --project-ref {ref}+ --project-ref {projectRef}</>)},comment: 'Deploy your function',},{- command: `curl -L -X POST 'https://${ref}.functions.supabase.${restUrlTld}/hello-world' -H 'Authorization: Bearer ${+ command: `curl -L -X POST 'https://${projectRef}.functions.supabase.${restUrlTld}/hello-world' -H 'Authorization: Bearer ${anonKey ?? '[YOUR ANON KEY]'}' --data '{"name":"Functions"}'`,description: 'Invokes the hello-world function',diff --git a/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx b/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsxindex a70a125cc0b..df8c4e89282 100644--- a/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx+++ b/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx@@ -1,19 +1,18 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { JwtSecretUpdateStatus } from '@supabase/shared-types/out/events'import Link from 'next/link'import { useState } from 'react'-import { useRouter } from 'next/router'-import { Input, IconLoader, IconAlertCircle } from 'ui'-import { JwtSecretUpdateStatus } from '@supabase/shared-types/out/events'-import { PermissionAction } from '@supabase/shared-types/out/constants'+import { IconAlertCircle, IconLoader, Input } from 'ui'-import { checkPermissions, useJwtSecretUpdateStatus, useProjectSettings } from 'hooks'-import { DEFAULT_PROJECT_API_SERVICE_ID } from 'lib/constants'import Snippets from 'components/to-be-cleaned/Docs/Snippets'-import Panel from 'components/ui/Panel'import SimpleCodeBlock from 'components/to-be-cleaned/SimpleCodeBlock'+import Panel from 'components/ui/Panel'+import { useProjectSettingsQuery } from 'data/config/project-settings-query'+import { checkPermissions, useJwtSecretUpdateStatus, useParams } from 'hooks'+import { DEFAULT_PROJECT_API_SERVICE_ID } from 'lib/constants'const APIKeys = () => {- const router = useRouter()- const { ref } = router.query+ const { ref: projectRef } = useParams()const availableLanguages = [{ name: 'Javascript', key: 'js' },@@ -22,22 +21,26 @@ const APIKeys = () => {const [selectedLanguage, setSelectedLanguage] = useState(availableLanguages[0])const {- services,+ data: settings,isError: isProjectSettingsError,isLoading: isProjectSettingsLoading,- } = useProjectSettings(ref as string | undefined)+ } = useProjectSettingsQuery({+ projectRef,+ })const {jwtSecretUpdateStatus,isError: isJwtSecretUpdateStatusError,isLoading: isJwtSecretUpdateStatusLoading,- }: any = useJwtSecretUpdateStatus(ref)+ }: any = useJwtSecretUpdateStatus(projectRef)const canReadAPIKeys = checkPermissions(PermissionAction.READ, 'service_api_keys')// Get the API service- const apiService = (services ?? []).find((x: any) => x.app.id == DEFAULT_PROJECT_API_SERVICE_ID)- const apiConfig = apiService?.app_config ?? {}+ const apiService = (settings?.services ?? []).find(+ (x: any) => x.app.id == DEFAULT_PROJECT_API_SERVICE_ID+ )+ const apiConfig = apiService?.app_configconst apiKeys = apiService?.service_api_keys ?? []// API keys should not be empty. However it can be populated with a delay on project creation@@ -45,7 +48,7 @@ const APIKeys = () => {const isNotUpdatingJwtSecret =jwtSecretUpdateStatus === undefined || jwtSecretUpdateStatus === JwtSecretUpdateStatus.Updated- const apiUrl = `https://${apiConfig.endpoint}`+ const apiUrl = `https://${apiConfig?.endpoint ?? '-'}`const anonKey = apiKeys.find((key: any) => key.tags === 'anon')const clientInitSnippet: any = Snippets.init(apiUrl)@@ -110,7 +113,7 @@ const APIKeys = () => {<div className="space-y-2"><p className="text-sm">API Key</p><div className="flex items-center space-x-1 -ml-1">- {anonKey.tags?.split(',').map((x: any, i: number) => (+ {anonKey?.tags.split(',').map((x: any, i: number) => (<code key={`${x}${i}`} className="text-xs">{x}</code>@@ -120,7 +123,7 @@ const APIKeys = () => {</div>}copy={canReadAPIKeys && isNotUpdatingJwtSecret}- reveal={anonKey.tags !== 'anon' && canReadAPIKeys && isNotUpdatingJwtSecret}+ reveal={anonKey?.tags !== 'anon' && canReadAPIKeys && isNotUpdatingJwtSecret}value={!canReadAPIKeys? 'You need additional permissions to view API keys'@@ -128,7 +131,7 @@ const APIKeys = () => {? 'JWT secret update failed, new API key may have issues': jwtSecretUpdateStatus === JwtSecretUpdateStatus.Updating? 'Updating JWT secret...'- : anonKey.api_key+ : anonKey?.api_key ?? '-'}onChange={() => {}}descriptionText={@@ -136,7 +139,7 @@ const APIKeys = () => {This key is safe to use in a browser if you have enabled Row Level Security (RLS)for your tables and configured policies. You may also use the service key whichcan be found{' '}- <Link href={`/project/${ref}/settings/api`}>+ <Link href={`/project/${projectRef}/settings/api`}><a className="text-brand-800 hover:text-brand-900 transition">here</a></Link>{' '}to bypass RLS.diff --git a/studio/components/interfaces/Settings/API/ServiceList.tsx b/studio/components/interfaces/Settings/API/ServiceList.tsxindex f1dcce06dca..fec6b7bd493 100644--- a/studio/components/interfaces/Settings/API/ServiceList.tsx+++ b/studio/components/interfaces/Settings/API/ServiceList.tsx@@ -1,33 +1,26 @@-import { FC, useEffect, useRef } from 'react'-import { useRouter } from 'next/router'import { JwtSecretUpdateError, JwtSecretUpdateStatus } from '@supabase/shared-types/out/events'+import { useEffect, useRef } from 'react'import { IconAlertCircle, Input } from 'ui'-import {- useStore,- useProjectSettings,- useProjectPostgrestConfig,- useJwtSecretUpdateStatus,-} from 'hooks'+import { useJwtSecretUpdateStatus, useParams, useProjectPostgrestConfig, useStore } from 'hooks'import Panel from 'components/ui/Panel'-import PostgrestConfig from './PostgrestConfig'import { DisplayApiSettings } from 'components/ui/ProjectSettings'+import { useProjectApiQuery } from 'data/config/project-api-query'import { JWT_SECRET_UPDATE_ERROR_MESSAGES } from './API.constants'import JWTSettings from './JWTSettings'+import PostgrestConfig from './PostgrestConfig'-interface Props {- projectRef: string-}--const ServiceList: FC<Props> = ({ projectRef }) => {+const ServiceList = () => {const { ui } = useStore()- const router = useRouter()- const { ref } = router.query- const { services, isError, mutateSettings } = useProjectSettings(ref as string | undefined)- const { mutateConfig } = useProjectPostgrestConfig(ref as string | undefined)- const { jwtSecretUpdateError, jwtSecretUpdateStatus }: any = useJwtSecretUpdateStatus(ref)+ const { ref: projectRef } = useParams()+ const { data: settings, isError } = useProjectApiQuery({+ projectRef,+ })++ const { mutateConfig } = useProjectPostgrestConfig(projectRef as string | undefined)+ const { jwtSecretUpdateError, jwtSecretUpdateStatus }: any = useJwtSecretUpdateStatus(projectRef)const previousJwtSecretUpdateStatus = useRef()const { Failed, Updated, Updating } = JwtSecretUpdateStatus@@ -39,7 +32,7 @@ const ServiceList: FC<Props> = ({ projectRef }) => {switch (jwtSecretUpdateStatus) {case Updated:mutateConfig()- mutateSettings()+ // mutateSettings()ui.setNotification({ category: 'success', message: 'Successfully updated JWT secret' })breakcase Failed:@@ -54,10 +47,7 @@ const ServiceList: FC<Props> = ({ projectRef }) => {previousJwtSecretUpdateStatus.current = jwtSecretUpdateStatus}, [jwtSecretUpdateStatus])- // Get the API service- const API_SERVICE_ID = 1- const apiService = services ? services.find((x: any) => x.app.id == API_SERVICE_ID) : {}- const apiConfig = apiService?.app_config+ const endpoint = settings?.autoApiService.app_config.endpoint ?? ''return (<>@@ -78,7 +68,7 @@ const ServiceList: FC<Props> = ({ projectRef }) => {readOnlydisabledclassName="input-mono"- value={`https://${apiConfig?.endpoint ?? '-'}`}+ value={`https://${endpoint ?? '-'}`}descriptionText="A RESTful endpoint for querying and managing your database."layout="horizontal"/>diff --git a/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainConfig.tsx b/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainConfig.tsxindex dde95501290..ae2222088a1 100644--- a/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainConfig.tsx+++ b/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainConfig.tsx@@ -3,7 +3,7 @@ import { observer } from 'mobx-react-lite'import { IconAlertCircle } from 'ui'import { useParams, useStore } from 'hooks'-import { useProjectSettingsQuery } from 'data/config/project-settings-query'+import { useProjectApiQuery } from 'data/config/project-api-query'import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'import Panel from 'components/ui/Panel'import { FormHeader } from 'components/ui/Forms'@@ -20,7 +20,7 @@ const CustomDomainConfig = () => {const { ref } = useParams()const tier = ui.selectedProject?.subscription_tier- const { isLoading: isSettingsLoading, data: settings } = useProjectSettingsQuery({+ const { isLoading: isSettingsLoading, data: settings } = useProjectApiQuery({projectRef: ref,})diff --git a/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainVerify.tsx b/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainVerify.tsxindex c8dee15035a..93e2d0c1e8e 100644--- a/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainVerify.tsx+++ b/studio/components/interfaces/Settings/General/CustomDomainConfig/CustomDomainVerify.tsx@@ -4,7 +4,7 @@ import { observer } from 'mobx-react-lite'import { Button, IconAlertCircle, IconExternalLink, IconHelpCircle, IconRefreshCw } from 'ui'import { useStore } from 'hooks'-import { ProjectSettingsResponse } from 'data/config/project-settings-query'+import { ProjectApiResponse } from 'data/config/project-api-query'import { CustomDomainResponse } from 'data/custom-domains/custom-domains-query'import { useCustomDomainDeleteMutation } from 'data/custom-domains/custom-domains-delete-mutation'import { useCustomDomainReverifyMutation } from 'data/custom-domains/custom-domains-reverify-mutation'@@ -15,7 +15,7 @@ import InformationBox from 'components/ui/InformationBox'export type CustomDomainVerifyProps = {projectRef?: stringcustomDomain: CustomDomainResponse- settings?: ProjectSettingsResponse+ settings?: ProjectApiResponse}const CustomDomainVerify = ({ projectRef, customDomain, settings }: CustomDomainVerifyProps) => {diff --git a/studio/components/layouts/StorageLayout/StorageLayout.tsx b/studio/components/layouts/StorageLayout/StorageLayout.tsxindex 6f6c3a13491..d259c3b5d8a 100644--- a/studio/components/layouts/StorageLayout/StorageLayout.tsx+++ b/studio/components/layouts/StorageLayout/StorageLayout.tsx@@ -3,7 +3,7 @@ import { useRouter } from 'next/router'import { find, filter, get as _get } from 'lodash'import { observer } from 'mobx-react-lite'-import { useProjectSettings, useStore, withAuth } from 'hooks'+import { useParams, useStore, withAuth } from 'hooks'import BaseLayout from 'components/layouts'import ProjectLayout from '../ProjectLayout/ProjectLayout'import StorageMenu from './StorageMenu'@@ -13,6 +13,7 @@ import CreateBucketModal from 'components/to-be-cleaned/Storage/CreateBucketModaimport DeleteBucketModal from 'components/to-be-cleaned/Storage/DeleteBucketModal'import ToggleBucketPublicModal from 'components/to-be-cleaned/Storage/ToggleBucketPublicModal'import NoPermission from 'components/ui/NoPermission'+import { useProjectApiQuery } from 'data/config/project-api-query'interface Props {title: string@@ -22,7 +23,7 @@ interface Props {const StorageLayout: FC<Props> = ({ title, children }) => {const { ui, meta } = useStore()const router = useRouter()- const { ref } = router.query+ const { ref: projectRef } = useParams()const storageExplorerStore = useStorageStore()const {@@ -39,20 +40,22 @@ const StorageLayout: FC<Props> = ({ title, children }) => {buckets,} = storageExplorerStore || {}- const { services, isLoading } = useProjectSettings(ref as string | undefined)- const apiService = find(services ?? [], (service) => service.app.id === 1)- const projectUrl = apiService?.app_config?.endpoint ?? ''- const serviceKey = find(apiService?.service_api_keys ?? [], (key) => key.tags === 'service_role')- const canAccessStorage = !isLoading && services && serviceKey+ const { data: settings, isLoading } = useProjectApiQuery({+ projectRef,+ })++ const projectUrl = settings?.autoApiService.app_config.endpoint ?? ''+ const serviceKey = settings?.autoApiService.serviceApiKey+ const canAccessStorage = !isLoading && settings && serviceKeyuseEffect(() => {- if (!isLoading && services) initializeStorageStore()+ if (!isLoading && settings) initializeStorageStore()}, [isLoading])const initializeStorageStore = async () => {if (projectUrl) {if (serviceKey) {- storageExplorerStore.initStore(ref, projectUrl, serviceKey.api_key)+ storageExplorerStore.initStore(projectRef, projectUrl, serviceKey)await storageExplorerStore.fetchBuckets()}} else {@@ -67,7 +70,7 @@ const StorageLayout: FC<Props> = ({ title, children }) => {const onSelectCreateBucket = async (bucketName: string, isPublic: boolean) => {const bucket = await createBucket(bucketName, isPublic)- if (bucket.name) router.push(`/project/${ref}/storage/buckets/${bucket.name}`)+ if (bucket.name) router.push(`/project/${projectRef}/storage/buckets/${bucket.name}`)}const onSelectDeleteBucket = async (bucket: any) => {diff --git a/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx b/studio/components/ui/ProjectSettings/DisplayApiSettings.tsxindex c691e0d5730..cb7dc29a9d4 100644--- a/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx+++ b/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx@@ -1,34 +1,34 @@-import { useRouter } from 'next/router'-import { IconAlertCircle, IconLoader, Input } from 'ui'-import { JwtSecretUpdateStatus } from '@supabase/shared-types/out/events'import { PermissionAction } from '@supabase/shared-types/out/constants'+import { JwtSecretUpdateStatus } from '@supabase/shared-types/out/events'+import { IconAlertCircle, IconLoader, Input } from 'ui'-import { checkPermissions, useJwtSecretUpdateStatus, useProjectSettings } from 'hooks'-import { DEFAULT_PROJECT_API_SERVICE_ID } from 'lib/constants'import Panel from 'components/ui/Panel'+import { useProjectSettingsQuery } from 'data/config/project-settings-query'+import { checkPermissions, useJwtSecretUpdateStatus, useParams } from 'hooks'+import { DEFAULT_PROJECT_API_SERVICE_ID } from 'lib/constants'const DisplayApiSettings = () => {- const router = useRouter()- const { ref } = router.query+ const { ref: projectRef } = useParams()const {- services,- error: projectSettingsError,+ data: settings,isError: isProjectSettingsError,isLoading: isProjectSettingsLoading,- } = useProjectSettings(ref as string | undefined)+ } = useProjectSettingsQuery({ projectRef })const {jwtSecretUpdateStatus,isError: isJwtSecretUpdateStatusError,isLoading: isJwtSecretUpdateStatusLoading,- }: any = useJwtSecretUpdateStatus(ref)+ }: any = useJwtSecretUpdateStatus(projectRef)const canReadAPIKeys = checkPermissions(PermissionAction.READ, 'service_api_keys')const isNotUpdatingJwtSecret =jwtSecretUpdateStatus === undefined || jwtSecretUpdateStatus === JwtSecretUpdateStatus.Updated// Get the API service- const apiService = (services ?? []).find((x: any) => x.app.id == DEFAULT_PROJECT_API_SERVICE_ID)+ const apiService = (settings?.services ?? []).find(+ (x: any) => x.app.id == DEFAULT_PROJECT_API_SERVICE_ID+ )const apiKeys = apiService?.service_api_keys ?? []// api keys should not be empty. However it can be populated with a delay on project creationconst isApiKeysEmpty = apiKeys.length === 0@@ -117,3 +117,140 @@ const DisplayApiSettings = () => {)}export default DisplayApiSettings++/*+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { JwtSecretUpdateStatus } from '@supabase/shared-types/out/events'+import { IconAlertCircle, IconLoader, Input } from 'ui'++import Panel from 'components/ui/Panel'+import { useProjectApiQuery } from 'data/config/project-api-query'+import { checkPermissions, useJwtSecretUpdateStatus, useParams } from 'hooks'++const DisplayApiSettings = () => {+ const { ref: projectRef } = useParams()+ const {+ data: settings,+ isError: isProjectSettingsError,+ isLoading: isProjectSettingsLoading,+ } = useProjectApiQuery({+ projectRef,+ })++ const {+ jwtSecretUpdateStatus,+ isError: isJwtSecretUpdateStatusError,+ isLoading: isJwtSecretUpdateStatusLoading,+ }: any = useJwtSecretUpdateStatus(projectRef)++ const canReadAPIKeys = checkPermissions(PermissionAction.READ, 'service_api_keys')++ const isNotUpdatingJwtSecret =+ jwtSecretUpdateStatus === undefined || jwtSecretUpdateStatus === JwtSecretUpdateStatus.Updated+ // Get the API service++ const apiKeys = settings?.autoApiService.service_api_keys ?? []+ // api keys should not be empty. However it can be populated with a delay on project creation+ const isApiKeysEmpty = apiKeys.length === 0++ const anonKey = settings?.autoApiService.defaultApiKey+ const serviceKey = settings?.autoApiService.serviceApiKey++ return (+ <Panel+ title={+ <div className="space-y-3">+ <h5 className="text-base">Project API keys</h5>+ <p className="text-sm text-scale-1000">+ Your API is secured behind an API gateway which requires an API Key for every request.+ <br />+ You can use the keys below to use Supabase client libraries.+ </p>+ </div>+ }+ >+ {isProjectSettingsError || isJwtSecretUpdateStatusError ? (+ <div className="flex items-center justify-center space-x-2 py-8">+ <IconAlertCircle size={16} strokeWidth={1.5} />+ <p className="text-sm text-scale-1100">+ {isProjectSettingsError ? 'Failed to retrieve API keys' : 'Failed to update JWT secret'}+ </p>+ </div>+ ) : isApiKeysEmpty || isProjectSettingsLoading || isJwtSecretUpdateStatusLoading ? (+ <div className="flex items-center justify-center space-x-2 py-8">+ <IconLoader className="animate-spin" size={16} strokeWidth={1.5} />+ <p className="text-sm text-scale-1100">+ {isProjectSettingsLoading || isApiKeysEmpty+ ? 'Retrieving API keys'+ : 'JWT secret is being updated'}+ </p>+ </div>+ ) : (+ <>+ <Panel.Content key={anonKey}>+ <Input+ readOnly+ disabled+ layout="horizontal"+ className="input-mono"+ // @ts-ignore+ label={+ <>+ <code className="text-xs text-code">anon</code>+ <code className="text-xs text-code">public</code>+ </>+ }+ copy={canReadAPIKeys && isNotUpdatingJwtSecret}+ value={+ !canReadAPIKeys+ ? 'You need additional permissions to view API keys'+ : jwtSecretUpdateStatus === JwtSecretUpdateStatus.Failed+ ? 'JWT secret update failed, new API key may have issues'+ : jwtSecretUpdateStatus === JwtSecretUpdateStatus.Updating+ ? 'Updating JWT secret...'+ : anonKey+ }+ onChange={() => {}}+ descriptionText="This key is safe to use in a browser if you have enabled Row Level Security for your tables and configured policies."+ />+ </Panel.Content>++ <Panel.Content+ key={serviceKey}+ className="border-t border-panel-border-interior-light dark:border-panel-border-interior-dark"+ >+ <Input+ readOnly+ disabled+ layout="horizontal"+ className="input-mono"+ // @ts-ignore+ label={+ <>+ <code className="text-xs text-code">service_role</code>+ <code className="bg-red-900 text-xs text-white">secret</code>+ </>+ }+ copy={canReadAPIKeys && isNotUpdatingJwtSecret}+ reveal={canReadAPIKeys && isNotUpdatingJwtSecret}+ value={+ !canReadAPIKeys+ ? 'You need additional permissions to view API keys'+ : jwtSecretUpdateStatus === JwtSecretUpdateStatus.Failed+ ? 'JWT secret update failed, new API key may have issues'+ : jwtSecretUpdateStatus === JwtSecretUpdateStatus.Updating+ ? 'Updating JWT secret...'+ : serviceKey+ }+ onChange={() => {}}+ descriptionText="This key has the ability to bypass Row Level Security. Never share it publicly."+ />+ </Panel.Content>+ </>+ )}+ </Panel>+ )+}+export default DisplayApiSettings++*/diff --git a/studio/components/ui/ProjectSettings/DisplayConfigSettings.tsx b/studio/components/ui/ProjectSettings/DisplayConfigSettings.tsxindex d43f8a3d478..ce804ef8d81 100644--- a/studio/components/ui/ProjectSettings/DisplayConfigSettings.tsx+++ b/studio/components/ui/ProjectSettings/DisplayConfigSettings.tsx@@ -1,32 +1,35 @@-import { FC } from 'react'-import { useRouter } from 'next/router'-import { Input, IconAlertCircle, IconLoader } from 'ui'import { JwtSecretUpdateStatus } from '@supabase/shared-types/out/events'-import { useJwtSecretUpdateStatus, useProjectSettings } from 'hooks'-import { DEFAULT_PROJECT_API_SERVICE_ID } from 'lib/constants'import Panel from 'components/ui/Panel'+import { useProjectSettingsQuery } from 'data/config/project-settings-query'+import { useJwtSecretUpdateStatus, useParams } from 'hooks'+import { DEFAULT_PROJECT_API_SERVICE_ID } from 'lib/constants'+import { FC } from 'react'+import { IconAlertCircle, IconLoader, Input } from 'ui'const DisplayConfigSettings = () => {- const router = useRouter()- const { ref } = router.query+ const { ref: projectRef } = useParams()const {- project,- services,+ data: settings,isLoading: isProjectSettingsLoading,isError: isProjectSettingsError,- } = useProjectSettings(ref as string | undefined)+ } = useProjectSettingsQuery({+ projectRef,+ })+const {isError: isJwtSecretUpdateStatusError,isLoading: isJwtSecretUpdateStatusLoading,jwtSecretUpdateStatus,- }: any = useJwtSecretUpdateStatus(ref)+ }: any = useJwtSecretUpdateStatus(projectRef)const isNotUpdatingJwtSecret =jwtSecretUpdateStatus === undefined || jwtSecretUpdateStatus === JwtSecretUpdateStatus.Updated// Get the API service- const jwtSecret = project?.jwt_secret ?? ''- const apiService = (services ?? []).find((x: any) => x.app.id == DEFAULT_PROJECT_API_SERVICE_ID)- const apiConfig = apiService?.app_config ?? {}+ const jwtSecret = settings?.project.jwt_secret ?? ''+ const apiService = (settings?.services ?? []).find(+ (x: any) => x.app.id == DEFAULT_PROJECT_API_SERVICE_ID+ )+ const apiConfig = apiService?.app_configreturn (<ConfigContentWrapper>@@ -55,7 +58,7 @@ const DisplayConfigSettings = () => {copydisabledclassName="input-mono"- value={`https://${apiConfig.endpoint}`}+ value={`https://${apiConfig?.endpoint ?? '-'}`}descriptionText="A RESTful endpoint for querying and managing your database."layout="horizontal"/>diff --git a/studio/data/config/keys.ts b/studio/data/config/keys.tsindex 875848a4247..baa6c204ebd 100644--- a/studio/data/config/keys.ts+++ b/studio/data/config/keys.ts@@ -1,3 +1,4 @@export const configKeys = {settings: (projectRef: string | undefined) => ['projects', projectRef, 'settings'] as const,+ api: (projectRef: string | undefined) => ['projects', projectRef, 'settings', 'api'] as const,}diff --git a/studio/data/config/project-api-query.ts b/studio/data/config/project-api-query.tsnew file mode 100644index 00000000000..11614a1ed4d--- /dev/null+++ b/studio/data/config/project-api-query.ts@@ -0,0 +1,116 @@+import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'+import { get } from 'lib/common/fetch'+import { API_URL } from 'lib/constants'+import { useCallback } from 'react'+import { configKeys } from './keys'++export type ProjectApiVariables = {+ projectRef?: string+}++export type Project = {+ id: number+ name: string+ ref: string+ status: string+ db_host: string+ db_name: string+ db_user: string+ db_schema: string+ db_port: number+ db_ssl: boolean+ services: Service[]+}++export type App = {+ id: number+ name: string+}++export type AppConfig = {+ endpoint: string+ db_schema: string+ realtime_multitenant_enabled: boolean+}++export type Service = {+ id: number+ name: string+ app_config: AppConfig+ app: App+ service_api_keys: ServiceApiKey[]+}++export type ServiceApiKey = {+ api_key_encrypted: string+ tags: string+ name: string+}++export type AutoApiService = Service & {+ endpoint: string+ restUrl: string+ project: Project+ defaultApiKey: string+ serviceApiKey: string+}++export type ProjectApiResponse = {+ project: Project+ autoApiService: AutoApiService+}++export async function getProjectApi({ projectRef }: ProjectApiVariables, signal?: AbortSignal) {+ if (!projectRef) {+ throw new Error('projectRef is required')+ }++ const response = await get(`${API_URL}/props/project/${projectRef}/api`, {+ signal,+ })+ if (response.error) {+ throw response.error+ }++ return response as ProjectApiResponse+}++export type ProjectApiData = Awaited<ReturnType<typeof getProjectApi>>+export type ProjectApiError = unknown++export const useProjectApiQuery = <TData = ProjectApiData>(+ { projectRef }: ProjectApiVariables,+ { enabled = true, ...options }: UseQueryOptions<ProjectApiData, ProjectApiError, TData> = {}+) =>+ useQuery<ProjectApiData, ProjectApiError, TData>(+ configKeys.api(projectRef),+ ({ signal }) => getProjectApi({ projectRef }, signal),+ {+ enabled: enabled && typeof projectRef !== 'undefined',+ refetchInterval(data, query) {+ if (!data) {+ return false+ }++ const { autoApiService } = data as unknown as ProjectApiData++ const apiKeys = autoApiService?.service_api_keys ?? []+ const interval = apiKeys.length === 0 ? 2000 : 0++ return interval+ },+ ...options,+ }+ )++export const useProjectApiPrefetch = ({ projectRef }: ProjectApiVariables) => {+ const client = useQueryClient()++ return useCallback(() => {+ if (projectRef) {+ client.prefetchQuery(configKeys.api(projectRef), ({ signal }) =>+ getProjectApi({ projectRef }, signal)+ )+ }+ }, [projectRef])+}diff --git a/studio/data/config/project-settings-query.ts b/studio/data/config/project-settings-query.tsindex ad473e32e38..4d8eb6bf769 100644--- a/studio/data/config/project-settings-query.ts+++ b/studio/data/config/project-settings-query.ts@@ -1,6 +1,6 @@import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query'import { get } from 'lib/common/fetch'-import { API_URL } from 'lib/constants'+import { API_URL, DEFAULT_PROJECT_API_SERVICE_ID } from 'lib/constants'import { useCallback } from 'react'import { configKeys } from './keys'@@ -13,18 +13,25 @@ export type Project = {name: stringref: stringstatus: string- db_host: string- db_name: string- db_user: string- db_schema: string+ inserted_at: string+ db_dns_name: stringdb_port: number+ db_name: stringdb_ssl: boolean+ db_host: string+ db_user: string+ cloud_provider: string+ region: stringservices: Service[]+ jwt_secret: string}-export type App = {+export type Service = {id: numbername: string+ app_config: AppConfig+ app: App+ service_api_keys: ServiceApiKey[]}export type AppConfig = {@@ -33,31 +40,21 @@ export type AppConfig = {realtime_multitenant_enabled: boolean}-export type Service = {+export type App = {id: numbername: string- app_config: AppConfig- app: App- service_api_keys: ServiceApiKey[]}export type ServiceApiKey = {api_key_encrypted: stringtags: stringname: string-}--export type AutoApiService = Service & {- endpoint: string- restUrl: string- project: Project- defaultApiKey: string- serviceApiKey: string+ api_key: string}export type ProjectSettingsResponse = {project: Project- autoApiService: AutoApiService+ services: Service[]}export async function getProjectSettings(@@ -68,7 +65,7 @@ export async function getProjectSettings(throw new Error('projectRef is required')}- const response = await get(`${API_URL}/props/project/${projectRef}/api`, {+ const response = await get(`${API_URL}/props/project/${projectRef}/settings`, {signal,})if (response.error) {@@ -94,13 +91,10 @@ export const useProjectSettingsQuery = <TData = ProjectSettingsData>({enabled: enabled && typeof projectRef !== 'undefined',refetchInterval(data, query) {- if (!data) {- return false- }-- const { autoApiService } = data as unknown as ProjectSettingsData-- const apiKeys = autoApiService?.service_api_keys ?? []+ const apiService = (+ (data as unknown as ProjectSettingsData | undefined)?.services ?? []+ ).find((x) => x.app.id == DEFAULT_PROJECT_API_SERVICE_ID)+ const apiKeys = apiService?.service_api_keys ?? []const interval = apiKeys.length === 0 ? 2000 : 0return intervaldiff --git a/studio/hooks/queries/index.ts b/studio/hooks/queries/index.tsindex aa3cd3421f8..18887b214f3 100644--- a/studio/hooks/queries/index.ts+++ b/studio/hooks/queries/index.ts@@ -3,7 +3,6 @@ export * from './useOrganizationDetail'export * from './useOrganizationRoles'export * from './useFreeProjectLimitCheck'export * from './useProjectAuthConfig'-export * from './useProjectSettings'export * from './useProjectSubscription'export * from './useSubscriptionStats'export * from './useProjectPostgrestConfig'diff --git a/studio/hooks/queries/useProjectSettings.ts b/studio/hooks/queries/useProjectSettings.tsdeleted file mode 100644index cccebec4bb1..00000000000--- a/studio/hooks/queries/useProjectSettings.ts+++ /dev/null@@ -1,31 +0,0 @@-import { get } from 'lib/common/fetch'-import { API_URL, DEFAULT_PROJECT_API_SERVICE_ID } from 'lib/constants'-import useSWR from 'swr'--export function useProjectSettings(ref?: string) {- const url = `${API_URL}/props/project/${ref}/settings`- const { data, error, mutate } = useSWR<any>(ref ? url : null, get, {- /**- * on project creation, the service_api_keys will be populated with a delay- * check for data.services.service_api_keys, return a valid refresh interval if it's empty- */- refreshInterval: function (data: any) {- const apiService = (data?.services ?? []).find(- (x: any) => x.app.id == DEFAULT_PROJECT_API_SERVICE_ID- )- const apiKeys = apiService?.service_api_keys ?? []- const interval = apiKeys.length === 0 ? 2000 : 0- return interval- },- })- const anyError = data?.error || error-- return {- mutateSettings: mutate,- project: anyError ? undefined : data?.project,- services: anyError ? undefined : data?.services,- error: anyError,- isLoading: !anyError && !data,- isError: !!anyError,- }-}diff --git a/studio/pages/project/[ref]/functions/[id]/details.tsx b/studio/pages/project/[ref]/functions/[id]/details.tsxindex 1f17b634105..8f4aa672881 100644--- a/studio/pages/project/[ref]/functions/[id]/details.tsx+++ b/studio/pages/project/[ref]/functions/[id]/details.tsx@@ -1,19 +1,18 @@import dayjs from 'dayjs'import { useEffect, useState } from 'react'-import { useRouter } from 'next/router'import { observer } from 'mobx-react-lite'import { IconGlobe, IconTerminal } from 'ui'import { PermissionAction } from '@supabase/shared-types/out/constants'import { NextPageWithLayout } from 'types'-import { checkPermissions, useProjectSettings, useStore } from 'hooks'+import { checkPermissions, useParams, useStore } from 'hooks'import FunctionsLayout from 'components/layouts/FunctionsLayout'import CommandRender from 'components/interfaces/Functions/CommandRender'import NoPermission from 'components/ui/NoPermission'+import { useProjectApiQuery } from 'data/config/project-api-query'const PageLayout: NextPageWithLayout = () => {- const router = useRouter()- const { ref, id } = router.query+ const { ref: projectRef, id } = useParams()const { functions, ui } = useStore()@@ -23,6 +22,10 @@ const PageLayout: NextPageWithLayout = () => {setSelectedFunction(functions.byId(id))}, [functions.isLoaded, ui.selectedProject])+ const { data: settings } = useProjectApiQuery({+ projectRef,+ })+// get the .co or .net TLD from the restUrlconst restUrl = ui.selectedProject?.restUrlconst restUrlTld = new URL(restUrl as string).hostname.split('.').pop()@@ -95,16 +98,12 @@ const PageLayout: NextPageWithLayout = () => {},]- const { services } = useProjectSettings(ref as string | undefined)-const API_SERVICE_ID = 1// Get the API service- const apiService = (services ?? []).find((x: any) => x.app.id == API_SERVICE_ID)- const apiKeys = apiService?.service_api_keys ?? []- const anonKey = apiKeys.find((x: any) => x.name === 'anon key')?.api_key+ const anonKey = settings?.autoApiService.defaultApiKey- const endpoint = apiService?.app_config.endpoint ?? ''+ const endpoint = settings?.autoApiService.app_config.endpoint ?? ''const endpointSections = endpoint.split('.')const functionsEndpoint = [...endpointSections.slice(0, 1),@@ -114,7 +113,7 @@ const PageLayout: NextPageWithLayout = () => {const invokeCommands: any = [{- command: `curl -L -X POST 'https://${ref}.functions.supabase.${restUrlTld}/${+ command: `curl -L -X POST 'https://${projectRef}.functions.supabase.${restUrlTld}/${selectedFunction?.slug}' -H 'Authorization: Bearer ${anonKey ?? '[YOUR ANON KEY]'}' --data '{"name":"Functions"}'`,description: 'Invokes the hello function',@@ -177,7 +176,7 @@ const PageLayout: NextPageWithLayout = () => {<div className="grid grid-cols-3"><span className="cols-span-1 mb-1 block text-sm text-scale-1000">Endpoint URL</span><div className="col-span-2">- <span className="w-full break-words text-sm text-scale-1200">{`https://${ref}.functions.supabase.co/${selectedFunction?.slug}`}</span>+ <span className="w-full break-words text-sm text-scale-1200">{`https://${projectRef}.functions.supabase.co/${selectedFunction?.slug}`}</span></div></div>diff --git a/studio/pages/project/[ref]/settings/api.tsx b/studio/pages/project/[ref]/settings/api.tsxindex 63af221d05f..618c9498d2c 100644--- a/studio/pages/project/[ref]/settings/api.tsx+++ b/studio/pages/project/[ref]/settings/api.tsx@@ -38,7 +38,7 @@ const ApiSettings: NextPageWithLayout = () => {return (<PageContext.Provider value={PageState}><div className="1xl:px-28 mx-auto flex flex-col gap-4 px-5 py-6 lg:px-16 xl:px-24 2xl:px-32">- <ServiceList projectRef={ref as string} />+ <ServiceList /></div></PageContext.Provider>)