Skip to content

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

Chore/sentry fixes 050624 (#27025)

Joshen Lim21890675e565
diff --git a/apps/studio/components/interfaces/Docs/ResourceContent.tsx b/apps/studio/components/interfaces/Docs/ResourceContent.tsx
index 151c1d371e4..599b8cc1e40 100644
--- a/apps/studio/components/interfaces/Docs/ResourceContent.tsx
+++ b/apps/studio/components/interfaces/Docs/ResourceContent.tsx
@@ -6,42 +6,53 @@ import Description from 'components/interfaces/Docs/Description'
import Param from 'components/interfaces/Docs/Param'
import Snippets from 'components/interfaces/Docs/Snippets'
import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'
+import { useProjectJsonSchemaQuery } from 'data/docs/project-json-schema-query'
import { useIsFeatureEnabled } from 'hooks'
+interface ResourceContentProps {
+ apiEndpoint: string
+ resourceId: string
+ resources: { [key: string]: { id: string; displayName: string; camelCase: string } }
+ selectedLang: 'bash' | 'js'
+ showApiKey: string
+ refreshDocs: () => void
+}
+
const ResourceContent = ({
- autoApiService,
+ apiEndpoint,
resourceId,
resources,
- definitions,
- paths,
selectedLang,
showApiKey,
refreshDocs,
-}: any) => {
+}: ResourceContentProps) => {
const { ref } = useParams()
const { data: customDomainData } = useCustomDomainsQuery({ projectRef: ref })
const { realtimeAll: realtimeEnabled } = useIsFeatureEnabled(['realtime:all'])
+ const { data: jsonSchema } = useProjectJsonSchemaQuery({ projectRef: ref })
+ const { paths, definitions } = jsonSchema || {}
+
const endpoint =
customDomainData?.customDomain?.status === 'active'
? `https://${customDomainData.customDomain.hostname}`
- : autoApiService.endpoint
-
- if (!paths || !definitions) return null
+ : apiEndpoint
const keyToShow = !!showApiKey ? showApiKey : 'SUPABASE_KEY'
- const resourcePaths = paths[`/${resourceId}`]
- const resourceDefinition = definitions[resourceId]
+ const resourcePaths = paths?.[`/${resourceId}`]
+ const resourceDefinition = definitions?.[resourceId]
const resourceMeta = resources[resourceId]
- const description = resourceDefinition?.description || null
+ const description = resourceDefinition?.description || ''
const methods = Object.keys(resourcePaths ?? {}).map((x) => x.toUpperCase())
- const properties = Object.entries(resourceDefinition.properties || []).map(([id, val]: any) => ({
+ const properties = Object.entries(resourceDefinition?.properties ?? []).map(([id, val]: any) => ({
...val,
id,
required: resourceDefinition?.required?.includes(id),
}))
+ if (!paths || !definitions) return null
+
return (
<>
<h2 className="doc-section__table-name text-foreground mt-0 flex items-center px-6 gap-2">
diff --git a/apps/studio/components/interfaces/ProjectAPIDocs/Content/Entity.tsx b/apps/studio/components/interfaces/ProjectAPIDocs/Content/Entity.tsx
index 5d35d677bd8..fda909b7295 100644
--- a/apps/studio/components/interfaces/ProjectAPIDocs/Content/Entity.tsx
+++ b/apps/studio/components/interfaces/ProjectAPIDocs/Content/Entity.tsx
@@ -36,6 +36,7 @@ const Entity = ({ language, apikey = '', endpoint = '' }: ContentProps) => {
const resource = snap.activeDocsSection[1]
const { data: jsonSchema, refetch } = useProjectJsonSchemaQuery({ projectRef: ref })
+
const definition = jsonSchema?.definitions?.[resource]
const columns =
definition !== undefined
diff --git a/apps/studio/components/interfaces/ProjectAPIDocs/Content/RPC.tsx b/apps/studio/components/interfaces/ProjectAPIDocs/Content/RPC.tsx
index a3b7410d771..22cb399f98f 100644
--- a/apps/studio/components/interfaces/ProjectAPIDocs/Content/RPC.tsx
+++ b/apps/studio/components/interfaces/ProjectAPIDocs/Content/RPC.tsx
@@ -24,7 +24,7 @@ const RPC = ({ language }: ContentProps) => {
const rpc = functions.find((fn) => fn.name === rpcName)
const rpcJsonSchema = jsonSchema?.paths[rpc?.path]
- const summary = rpcJsonSchema?.post.summary
+ const summary = rpcJsonSchema?.post?.summary
const parameters = rpc?.get.parameters ?? []
useEffect(() => {
diff --git a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.utils.ts b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.utils.ts
index ac266b34b02..7a58ea07e25 100644
--- a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.utils.ts
+++ b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.utils.ts
@@ -17,14 +17,18 @@ export const isValidAddress = (address: string) => {
}
export const checkIfPrivate = (type: 'IPv4' | 'IPv6', cidr: string) => {
- if (type === 'IPv4') {
- const address = IPv4CidrRange.fromCidr(`${cidr}/32`)
- const res = privateIPv4Ranges.map((range) => address.inside(range))
- return res.includes(true)
- } else {
- const address = IPv6CidrRange.fromCidr(`${cidr}/128`)
- const res = privateIPv6Ranges.map((range) => address.inside(range))
- return res.includes(true)
+ try {
+ if (type === 'IPv4') {
+ const address = IPv4CidrRange.fromCidr(`${cidr}/32`)
+ const res = privateIPv4Ranges.map((range) => address.inside(range))
+ return res.includes(true)
+ } else {
+ const address = IPv6CidrRange.fromCidr(`${cidr}/128`)
+ const res = privateIPv6Ranges.map((range) => address.inside(range))
+ return res.includes(true)
+ }
+ } catch (error) {
+ return false
}
}
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx
index 37aab17aa1f..ddd9dfe93e1 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx
@@ -116,7 +116,7 @@ const InstanceConfigurationUI = () => {
const nodes = useMemo(
() =>
- isSuccessReplicas && isSuccessLoadBalancers
+ isSuccessReplicas && isSuccessLoadBalancers && primary !== undefined
? generateNodes({
primary,
replicas,
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.utils.ts b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.utils.ts
index 208150570f2..be22cf22df4 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.utils.ts
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.utils.ts
@@ -1,17 +1,15 @@
import dagre from '@dagrejs/dagre'
+import { groupBy } from 'lodash'
import { Edge, Node, Position } from 'reactflow'
+import type { LoadBalancer } from 'data/read-replicas/load-balancers-query'
+import type { Database } from 'data/read-replicas/replicas-query'
import {
AVAILABLE_REPLICA_REGIONS,
NODE_ROW_HEIGHT,
NODE_SEP,
NODE_WIDTH,
} from './InstanceConfiguration.constants'
-import { groupBy } from 'lodash'
-import type { Database } from 'data/read-replicas/replicas-query'
-import type { LoadBalancer } from 'data/read-replicas/load-balancers-query'
-import { DatabaseStatus } from 'data/read-replicas/replicas-status-query'
-import { AWS_REGIONS } from 'lib/constants'
// [Joshen] Just FYI the nodes generation assumes each project only has one load balancer
// Will need to change if this eventually becomes otherwise
diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
index 11f28972898..f695db994fd 100644
--- a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
@@ -445,6 +445,7 @@ export const fillTimeseries = (
'Data error, filling timeseries dynamically with more than 10k data points degrades performance.'
)
}
+
for (let i = 0; i <= diff; i++) {
const dateToMaybeAdd = minDate.add(i, truncation as dayjs.ManipulateType)
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
index d45c5761e0c..c4aec7cb423 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.tsx
@@ -213,7 +213,7 @@ const TableEditor = ({
setFkRelations([])
} else {
const tableFields = generateTableFieldFromPostgresTable(
- table!,
+ table,
foreignKeyMeta || [],
isDuplicating,
isRealtimeEnabled
diff --git a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.utils.ts b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.utils.ts
index 82bd8a63d67..0ce7ef75465 100644
--- a/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.utils.ts
+++ b/apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.utils.ts
@@ -46,7 +46,7 @@ export const generateTableFieldFromPostgresTable = (
name: isDuplicating ? `${table.name}_duplicate` : table.name,
comment: isDuplicating ? `This is a duplicate of ${table.name}` : table?.comment ?? '',
// @ts-ignore
- columns: table.columns.map((column: PostgresColumn) => {
+ columns: (table?.columns ?? []).map((column: PostgresColumn) => {
return generateColumnFieldFromPostgresColumn(column, table, foreignKeys)
}),
isRLSEnabled: table.rls_enabled,
diff --git a/apps/studio/data/config/project-api-query.ts b/apps/studio/data/config/project-api-query.ts
index ae1e960a9d8..51ab33af0a8 100644
--- a/apps/studio/data/config/project-api-query.ts
+++ b/apps/studio/data/config/project-api-query.ts
@@ -1,79 +1,30 @@
import { useQuery, UseQueryOptions } from '@tanstack/react-query'
-import { get } from 'lib/common/fetch'
-import { API_URL } from 'lib/constants'
-import { configKeys } from './keys'
+
+import { components } from 'api-types'
+import { get, handleError } from 'data/fetchers'
import type { ResponseError } from 'types'
+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 & {
- protocol: 'https' | 'http'
- endpoint: string
- restUrl: string
- project: Project
- defaultApiKey: string
- serviceApiKey: string
-}
+export type AutoApiService = components['schemas']['AutoApiService']
export type ProjectApiResponse = {
- project: Project
autoApiService: AutoApiService
}
export async function getProjectApi({ projectRef }: ProjectApiVariables, signal?: AbortSignal) {
- if (!projectRef) {
- throw new Error('projectRef is required')
- }
+ if (!projectRef) throw new Error('projectRef is required')
- const response = await get(`${API_URL}/props/project/${projectRef}/api`, {
+ const { data, error } = await get('/platform/props/project/{ref}/api', {
+ params: { path: { ref: projectRef } },
signal,
})
- if (response.error) {
- throw response.error
- }
- return response as ProjectApiResponse
+ if (error) handleError(error)
+ return data
}
export type ProjectApiData = Awaited<ReturnType<typeof getProjectApi>>
diff --git a/apps/studio/data/docs/project-json-schema-query.ts b/apps/studio/data/docs/project-json-schema-query.ts
index 43bc304a840..54aeae44a1b 100644
--- a/apps/studio/data/docs/project-json-schema-query.ts
+++ b/apps/studio/data/docs/project-json-schema-query.ts
@@ -1,30 +1,92 @@
import { useQuery, UseQueryOptions } from '@tanstack/react-query'
-import { get } from 'lib/common/fetch'
-import { API_URL } from 'lib/constants'
+
+import { get, handleError } from 'data/fetchers'
+import { ResponseError } from 'types'
import { docsKeys } from './keys'
export type ProjectJsonSchemaVariables = {
projectRef?: string
}
-export type ProjectJsonSchemaResponse = any
+type ProjectJsonSchemaMethod = {
+ tags: string[]
+ summary: string
+ responses: {
+ [key: string]: any
+ }
+ parameters: { [key: string]: string }[]
+}
+
+export type ProjectJsonSchemaDefinitions = {
+ [key: string]: {
+ type: string
+ description: string
+ required: string[]
+ properties: {
+ [key: string]: {
+ type: string
+ format: string
+ description?: string
+ enum?: string[]
+ }
+ }
+ }
+}
+
+export type ProjectJsonSchemaPaths = {
+ [key: string]: {
+ get?: ProjectJsonSchemaMethod
+ post?: ProjectJsonSchemaMethod
+ patch?: ProjectJsonSchemaMethod
+ delete?: ProjectJsonSchemaMethod
+ }
+}
+
+export type ProjectJsonSchemaResponse = {
+ basePath: string
+ consumes: string[]
+ definitions: ProjectJsonSchemaDefinitions
+ externalDocs: { description: string; url: string }
+ host: string
+ info: {
+ title: string
+ description: string
+ version: string
+ }
+ parameters: {
+ [key: string]: {
+ default?: string
+ description: string
+ in: string
+ name: string
+ required: boolean
+ type?: string
+ schema?: { [key: string]: string }
+ }
+ }
+ paths: ProjectJsonSchemaPaths
+ produces: string[]
+ schemes: string[]
+ swagger: string
+}
export async function getProjectJsonSchema(
{ projectRef }: ProjectJsonSchemaVariables,
signal?: AbortSignal
) {
- if (!projectRef) {
- throw new Error('projectRef is required')
- }
+ if (!projectRef) throw new Error('projectRef is required')
+
+ const { data, error } = await get('/platform/projects/{ref}/api/rest', {
+ params: { path: { ref: projectRef } },
+ signal,
+ })
- const url = `${API_URL}/projects/${projectRef}/api/rest`
- const response = await get(url, { signal })
- if (response.error) throw response.error
- return response as ProjectJsonSchemaResponse
+ if (error) handleError(error)
+ return data as unknown as ProjectJsonSchemaResponse
}
export type ProjectJsonSchemaData = Awaited<ReturnType<typeof getProjectJsonSchema>>
-export type ProjectJsonSchemaError = unknown
+export type ProjectJsonSchemaError = ResponseError
export const useProjectJsonSchemaQuery = <TData = ProjectJsonSchemaData>(
{ projectRef }: ProjectJsonSchemaVariables,
diff --git a/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx b/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx
index 4d67db79691..b4270943235 100644
--- a/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx
+++ b/apps/studio/localStores/storageExplorer/StorageExplorerStore.tsx
@@ -1318,7 +1318,7 @@ class StorageExplorerStore {
await batchedPromises.reduce(async (previousPromise, nextBatch) => {
await previousPromise
await Promise.all(nextBatch.map((batch) => batch()))
- toast.loader(
+ toast.loading(
<ToastLoader
progress={progress * 100}
message={`Renaming folder to ${newName}`}
@@ -1342,7 +1342,7 @@ class StorageExplorerStore {
)
this.filePreviewCache = updatedFilePreviewCache
} catch (e) {
- toast.error(`Failed to rename folder to ${newName}`, { id: toastId })
+ toast.error(`Failed to rename folder to ${newName}: ${e.message}`, { id: toastId })
}
}
diff --git a/apps/studio/pages/project/[ref]/api/index.tsx b/apps/studio/pages/project/[ref]/api/index.tsx
index bb4ddc1aaee..4d26875503a 100644
--- a/apps/studio/pages/project/[ref]/api/index.tsx
+++ b/apps/studio/pages/project/[ref]/api/index.tsx
@@ -1,7 +1,5 @@
import { useParams } from 'common'
-import { observer, useLocalObservable } from 'mobx-react-lite'
-import { useRouter } from 'next/router'
-import { createContext, useContext, useEffect, useState } from 'react'
+import { useState } from 'react'
import { GeneralContent, ResourceContent, RpcContent } from 'components/interfaces/Docs'
import LangSelector from 'components/interfaces/Docs/LangSelector'
@@ -12,56 +10,18 @@ import { useProjectJsonSchemaQuery } from 'data/docs/project-json-schema-query'
import { snakeToCamel } from 'lib/helpers'
import type { NextPageWithLayout } from 'types'
-const PageContext = createContext(null)
-
const PageConfig: NextPageWithLayout = () => {
- const PageState: any = useLocalObservable(() => ({
- projectRef: '',
- jsonSchema: {},
- resources: {},
- rpcs: {},
- setJsonSchema(value: any) {
- const { paths } = value || {}
- const functionPath = 'rpc/'
- let resources: any = {}
- let rpcs: any = {}
-
- Object.entries(paths || []).forEach(([name, val]) => {
- let trimmed = name.slice(1)
- let id = trimmed.replace(functionPath, '')
- let displayName = id.replace(/_/g, ' ')
- let camelCase = snakeToCamel(id)
- let enriched = { id, displayName, camelCase }
- if (!trimmed.length) return
- else if (trimmed.includes(functionPath)) rpcs[id] = enriched
- else resources[id] = enriched
- })
-
- PageState.jsonSchema = value
- PageState.resources = resources
- PageState.rpcs = rpcs
- },
- }))
-
- const router = useRouter()
- const { query } = router
- PageState.projectRef = query.ref
-
- return (
- <PageContext.Provider value={PageState}>
- <DocView />
- </PageContext.Provider>
- )
+ return <DocView />
}
PageConfig.getLayout = (page) => <DocsLayout title="API">{page}</DocsLayout>
-export default observer(PageConfig)
+export default PageConfig
-const DEFAULT_KEY = { name: 'hide', key: 'SUPABASE_KEY' }
+const DocView = () => {
+ const functionPath = 'rpc/'
+ const DEFAULT_KEY = { name: 'hide', key: 'SUPABASE_KEY' }
-const DocView = observer(() => {
- const PageState: any = useContext(PageContext)
const { ref: projectRef, page, resource, rpc } = useParams()
const [selectedLang, setSelectedLang] = useState<any>('js')
const [showApiKey, setShowApiKey] = useState<any>(DEFAULT_KEY)
@@ -73,6 +33,7 @@ const DocView = observer(() => {
const {
data: jsonSchema,
error: jsonSchemaError,
+ isLoading,
refetch,
} = useProjectJsonSchemaQuery({ projectRef })
const { data: customDomainData } = useCustomDomainsQuery({ projectRef })
@@ -84,13 +45,44 @@ const DocView = observer(() => {
? `https://${customDomainData.customDomain?.hostname}`
: `${data?.autoApiService.protocol ?? 'https'}://${data?.autoApiService.endpoint ?? '-'}`
- const { paths, definitions } = PageState.jsonSchema || {}
+ const { paths } = jsonSchema || {}
const PAGE_KEY: any = resource || rpc || page || 'index'
const autoApiService = { ...(data?.autoApiService ?? {}), endpoint }
- useEffect(() => {
- PageState.setJsonSchema(jsonSchema)
- }, [jsonSchema])
+ const { resources, rpcs } = Object.entries(paths || {}).reduce(
+ (a, [name]) => {
+ const trimmedName = name.slice(1)
+ const id = trimmedName.replace(functionPath, '')
+
+ const displayName = id.replace(/_/g, ' ')
+ const camelCase = snakeToCamel(id)
+ const enriched = { id, displayName, camelCase }
+
+ if (!trimmedName.length) {
+ return a
+ }
+
+ return {
+ resources: {
+ ...a.resources,
+ ...(!trimmedName.includes(functionPath)
+ ? {
+ [id]: enriched,
+ }
+ : {}),
+ },
+ rpcs: {
+ ...a.rpcs,
+ ...(trimmedName.includes(functionPath)
+ ? {
+ [id]: enriched,
+ }
+ : {}),
+ },
+ }
+ },
+ { resources: {}, rpcs: {} }
+ )
if (error || jsonSchemaError) {
return (
@@ -103,7 +95,7 @@ const DocView = observer(() => {
)
}
- if (!data || !jsonSchema || !PageState.jsonSchema) {
+ if (isLoading || !data || !jsonSchema) {
return (
<div className="p-6 mx-auto text-center sm:w-full md:w-3/4">
<h3 className="text-xl">Building docs ...</h3>
@@ -127,12 +119,10 @@ const DocView = observer(() => {
<div>
{resource ? (
<ResourceContent
- autoApiService={autoApiService}
+ apiEndpoint={endpoint}
selectedLang={selectedLang}
resourceId={resource}
- resources={PageState.resources}
- definitions={definitions}
- paths={paths}
+ resources={resources}
showApiKey={showApiKey.key}
refreshDocs={refreshDocs}
/>
@@ -142,7 +132,7 @@ const DocView = observer(() => {
selectedLang={selectedLang}
rpcId={rpc}
paths={paths}
- rpcs={PageState.rpcs}
+ rpcs={rpcs}
showApiKey={showApiKey.key}
refreshDocs={refreshDocs}
/>
@@ -158,4 +148,4 @@ const DocView = observer(() => {
</div>
</div>
)
-})
+}