Skip to content

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

Chore/deprecate lib common fetch (#36503)

Joshen Lim669a96bed8c5
diff --git a/apps/studio/components/layouts/ProjectLayout/BuildingState.tsx b/apps/studio/components/layouts/ProjectLayout/BuildingState.tsx
index e6e1589c44b..c8f9726cc15 100644
--- a/apps/studio/components/layouts/ProjectLayout/BuildingState.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/BuildingState.tsx
@@ -1,50 +1,39 @@
import { useQueryClient } from '@tanstack/react-query'
-import ClientLibrary from 'components/interfaces/Home/ClientLibrary'
-import ExampleProject from 'components/interfaces/Home/ExampleProject'
-import { CLIENT_LIBRARIES, EXAMPLE_PROJECTS } from 'components/interfaces/Home/Home.constants'
+import { ArrowRight, Loader2 } from 'lucide-react'
import Link from 'next/link'
-import { useEffect, useRef } from 'react'
import { useParams } from 'common'
+import ClientLibrary from 'components/interfaces/Home/ClientLibrary'
+import ExampleProject from 'components/interfaces/Home/ExampleProject'
+import { CLIENT_LIBRARIES, EXAMPLE_PROJECTS } from 'components/interfaces/Home/Home.constants'
import { DisplayApiSettings, DisplayConfigSettings } from 'components/ui/ProjectSettings'
import { invalidateProjectDetailsQuery } from 'data/projects/project-detail-query'
+import { useProjectStatusQuery } from 'data/projects/project-status-query'
import { invalidateProjectsQuery } from 'data/projects/projects-query'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
-import { getWithTimeout } from 'lib/common/fetch'
-import { API_URL, PROJECT_STATUS } from 'lib/constants'
-import { ArrowRight, Loader2 } from 'lucide-react'
+import { PROJECT_STATUS } from 'lib/constants'
import { Badge, Button } from 'ui'
const BuildingState = () => {
const { ref } = useParams()
const project = useSelectedProject()
const queryClient = useQueryClient()
- const checkServerInterval = useRef<number>()
-
- // TODO: move to react-query
- async function checkServer() {
- if (!project) return
- const projectStatus = await getWithTimeout(`${API_URL}/projects/${project.ref}/status`, {
- timeout: 2000,
- })
- if (projectStatus && !projectStatus.error) {
- const { status } = projectStatus
- if (status === PROJECT_STATUS.ACTIVE_HEALTHY) {
- clearInterval(checkServerInterval.current)
- if (ref) await invalidateProjectDetailsQuery(queryClient, ref)
- await invalidateProjectsQuery(queryClient)
- }
+ useProjectStatusQuery(
+ { projectRef: ref },
+ {
+ enabled: project?.status !== PROJECT_STATUS.ACTIVE_HEALTHY,
+ refetchInterval: (res) => {
+ return res?.status === PROJECT_STATUS.ACTIVE_HEALTHY ? false : 4000
+ },
+ onSuccess: async (res) => {
+ if (res.status === PROJECT_STATUS.ACTIVE_HEALTHY) {
+ if (ref) invalidateProjectDetailsQuery(queryClient, ref)
+ invalidateProjectsQuery(queryClient)
+ }
+ },
}
- }
-
- useEffect(() => {
- // check server status every 4s
- checkServerInterval.current = window.setInterval(checkServer, 4000)
- return () => {
- clearInterval(checkServerInterval.current)
- }
- }, [])
+ )
if (project === undefined) return null
diff --git a/apps/studio/components/layouts/ProjectLayout/RestoringState.tsx b/apps/studio/components/layouts/ProjectLayout/RestoringState.tsx
index 6cbae550a21..f6a4517eb23 100644
--- a/apps/studio/components/layouts/ProjectLayout/RestoringState.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/RestoringState.tsx
@@ -1,16 +1,15 @@
import { useQueryClient } from '@tanstack/react-query'
import { CheckCircle, Download, Loader } from 'lucide-react'
import Link from 'next/link'
-import { useEffect, useRef, useState } from 'react'
+import { useState } from 'react'
import { useParams } from 'common'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useBackupDownloadMutation } from 'data/database/backup-download-mutation'
import { useDownloadableBackupQuery } from 'data/database/backup-query'
-import { projectKeys } from 'data/projects/keys'
import { invalidateProjectDetailsQuery } from 'data/projects/project-detail-query'
-import { getWithTimeout } from 'lib/common/fetch'
-import { API_URL, PROJECT_STATUS } from 'lib/constants'
+import { useProjectStatusQuery } from 'data/projects/project-status-query'
+import { PROJECT_STATUS } from 'lib/constants'
import { Button } from 'ui'
import { useProjectContext } from './ProjectContext'
@@ -18,7 +17,6 @@ const RestoringState = () => {
const { ref } = useParams()
const queryClient = useQueryClient()
const { project } = useProjectContext()
- const checkServerInterval = useRef<number>()
const [loading, setLoading] = useState(false)
const [isCompleted, setIsCompleted] = useState(false)
@@ -27,6 +25,23 @@ const RestoringState = () => {
const backups = data?.backups ?? []
const logicalBackups = backups.filter((b) => !b.isPhysicalBackup)
+ useProjectStatusQuery(
+ { projectRef: ref },
+ {
+ enabled: project?.status !== PROJECT_STATUS.ACTIVE_HEALTHY,
+ refetchInterval: (res) => {
+ return res?.status === PROJECT_STATUS.ACTIVE_HEALTHY ? false : 4000
+ },
+ onSuccess: async (res) => {
+ if (res.status === PROJECT_STATUS.ACTIVE_HEALTHY) {
+ setIsCompleted(true)
+ } else {
+ if (ref) invalidateProjectDetailsQuery(queryClient, ref)
+ }
+ },
+ }
+ )
+
const { mutate: downloadBackup, isLoading: isDownloading } = useBackupDownloadMutation({
onSuccess: (res) => {
const { fileUrl } = res
@@ -47,23 +62,6 @@ const RestoringState = () => {
downloadBackup({ ref, backup: logicalBackups[0] })
}
- async function checkServer() {
- if (!project) return
-
- const projectStatus = await getWithTimeout(`${API_URL}/projects/${project.ref}/status`, {
- timeout: 2000,
- })
- if (projectStatus && !projectStatus.error) {
- const { status } = projectStatus
- if (status === PROJECT_STATUS.ACTIVE_HEALTHY) {
- clearInterval(checkServerInterval.current)
- setIsCompleted(true)
- } else {
- queryClient.invalidateQueries(projectKeys.detail(ref))
- }
- }
- }
-
const onConfirm = async () => {
if (!project) return console.error('Project is required')
@@ -71,11 +69,6 @@ const RestoringState = () => {
if (ref) await invalidateProjectDetailsQuery(queryClient, ref)
}
- useEffect(() => {
- checkServerInterval.current = window.setInterval(checkServer, 4000)
- return () => clearInterval(checkServerInterval.current)
- }, [])
-
return (
<div className="flex items-center justify-center h-full">
<div className="bg-surface-100 border border-overlay rounded-md w-3/4 lg:w-1/2">
diff --git a/apps/studio/data/fetchers.ts b/apps/studio/data/fetchers.ts
index a4c4ad6f4cd..d3849c3e83e 100644
--- a/apps/studio/data/fetchers.ts
+++ b/apps/studio/data/fetchers.ts
@@ -160,3 +160,55 @@ export const handleError = (error: unknown): never => {
// up in the UI.
throw new ResponseError(undefined)
}
+
+// [Joshen] The methods below are brought over from lib/common/fetchers because we still need them
+// primarily for our own endpoints in the dashboard repo. So consolidating all the fetch methods into here.
+
+async function handleFetchResponse<T>(response: Response): Promise<T | ResponseError> {
+ const contentType = response.headers.get('Content-Type')
+ if (contentType === 'application/octet-stream') return response as any
+ try {
+ const resTxt = await response.text()
+ try {
+ // try to parse response text as json
+ return JSON.parse(resTxt)
+ } catch (err) {
+ // return as text plain
+ return resTxt as any
+ }
+ } catch (e) {
+ return handleError(response) as T | ResponseError
+ }
+}
+
+/**
+ * To be used only for dashboard API endpoints. Use `fetch` directly if calling a non dashboard API endpoint
+ *
+ * Exception for `bucket-object-download-mutation` as openapi-fetch doesn't support octet-stream responses
+ */
+export async function fetchPost<T = any>(
+ url: string,
+ data: { [prop: string]: any },
+ options?: { [prop: string]: any }
+): Promise<T | ResponseError> {
+ try {
+ const { headers: otherHeaders, abortSignal, ...otherOptions } = options ?? {}
+ const headers = await constructHeaders({
+ 'Content-Type': 'application/json',
+ ...DEFAULT_HEADERS,
+ ...otherHeaders,
+ })
+ const response = await fetch(url, {
+ method: 'POST',
+ body: JSON.stringify(data),
+ referrerPolicy: 'no-referrer-when-downgrade',
+ headers,
+ ...otherOptions,
+ signal: abortSignal,
+ })
+ if (!response.ok) return handleError(response)
+ return handleFetchResponse(response)
+ } catch (error) {
+ return handleError(error)
+ }
+}
diff --git a/apps/studio/data/profile/profile-create-mutation.ts b/apps/studio/data/profile/profile-create-mutation.ts
index f4c674300d2..0b373597a9f 100644
--- a/apps/studio/data/profile/profile-create-mutation.ts
+++ b/apps/studio/data/profile/profile-create-mutation.ts
@@ -1,23 +1,20 @@
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
+import { components } from 'api-types'
+import { handleError, post } from 'data/fetchers'
import { organizationKeys } from 'data/organizations/keys'
import { permissionKeys } from 'data/permissions/keys'
-import { post } from 'lib/common/fetch'
-import { API_URL } from 'lib/constants'
import type { ResponseError } from 'types'
import { profileKeys } from './keys'
-import type { Profile } from './types'
-export type ProfileResponse = Profile
+export type ProfileResponse = components['schemas']['ProfileResponse']
export async function createProfile() {
- const response = await post(`${API_URL}/profile`, {})
- if (response.error) {
- throw response.error
- }
+ const { data, error } = await post('/platform/profile')
- return response as ProfileResponse
+ if (error) handleError(error)
+ return data
}
type ProfileCreateData = Awaited<ReturnType<typeof createProfile>>
diff --git a/apps/studio/data/service-status/edge-functions-status-query.ts b/apps/studio/data/service-status/edge-functions-status-query.ts
index 9010e058064..ea97a0b4141 100644
--- a/apps/studio/data/service-status/edge-functions-status-query.ts
+++ b/apps/studio/data/service-status/edge-functions-status-query.ts
@@ -1,6 +1,5 @@
import { useQuery, UseQueryOptions } from '@tanstack/react-query'
-import { get } from 'lib/common/fetch'
import type { ResponseError } from 'types'
import { serviceStatusKeys } from './keys'
@@ -9,10 +8,16 @@ export type EdgeFunctionServiceStatusVariables = {
}
export async function getEdgeFunctionServiceStatus(signal?: AbortSignal) {
- const res = await get(`https://obuldanrptloktxcffvn.supabase.co/functions/v1/health-check`, {
- signal,
- })
- return res as { healthy: boolean }
+ try {
+ const res = await fetch('https://obuldanrptloktxcffvn.supabase.co/functions/v1/health-check', {
+ method: 'GET',
+ signal,
+ })
+ const response = await res.json()
+ return response as { healthy: boolean }
+ } catch (err) {
+ return { healthy: false }
+ }
}
export type EdgeFunctionServiceStatusData = Awaited<ReturnType<typeof getEdgeFunctionServiceStatus>>
diff --git a/apps/studio/data/storage/bucket-object-download-mutation.ts b/apps/studio/data/storage/bucket-object-download-mutation.ts
index dca56be8d93..02073d937ff 100644
--- a/apps/studio/data/storage/bucket-object-download-mutation.ts
+++ b/apps/studio/data/storage/bucket-object-download-mutation.ts
@@ -2,7 +2,7 @@ import { UseMutationOptions, useMutation } from '@tanstack/react-query'
import { toast } from 'sonner'
import { components } from 'data/api'
-import { post } from 'lib/common/fetch'
+import { fetchPost } from 'data/fetchers'
import { API_URL, IS_PLATFORM } from 'lib/constants'
import { ResponseError } from 'types'
@@ -18,15 +18,9 @@ export const downloadBucketObject = async (
) => {
if (!bucketId) throw new Error('bucketId is required')
- // [Joshen] JFYI we have to use lib/common/fetch post as post from openapi-fetch doesn't support receiving octet-streams
- // Opting to hard code /platform for non platform just for this particular mutation, so that it's clear what's happening
- const response = await post(
+ const response = await fetchPost(
`${API_URL}${IS_PLATFORM ? '' : '/platform'}/storage/${projectRef}/buckets/${bucketId}/objects/download`,
- {
- path,
- options,
- abortSignal: signal,
- }
+ { path, options, abortSignal: signal }
)
if (response.error) throw response.error
diff --git a/apps/studio/lib/common/fetch/base.ts b/apps/studio/lib/common/fetch/base.ts
index f9bf3c87aa7..3f000da9971 100644
--- a/apps/studio/lib/common/fetch/base.ts
+++ b/apps/studio/lib/common/fetch/base.ts
@@ -15,7 +15,6 @@ export async function handleResponse<T>(
): Promise<SupaResponse<T>> {
const contentType = response.headers.get('Content-Type')
if (contentType === 'application/octet-stream') return response as any
-
try {
const resTxt = await response.text()
try {
diff --git a/apps/studio/lib/common/fetch/get.ts b/apps/studio/lib/common/fetch/get.ts
index 0d9382c9529..b1f912934c9 100644
--- a/apps/studio/lib/common/fetch/get.ts
+++ b/apps/studio/lib/common/fetch/get.ts
@@ -25,30 +25,3 @@ export async function get<T = any>(
return handleError(error, requestId)
}
}
-
-export async function getWithTimeout<T = any>(
- url: string,
- options?: { [prop: string]: any }
-): Promise<SupaResponse<T>> {
- const requestId = uuidv4()
- try {
- const timeout = options?.timeout ?? 60000
- const controller = new AbortController()
- const id = setTimeout(() => controller.abort(), timeout)
- const { headers: optionHeaders, ...otherOptions } = options ?? {}
- const headers = await constructHeaders(requestId, optionHeaders)
- const response = await fetch(url, {
- method: 'GET',
- referrerPolicy: 'no-referrer-when-downgrade',
- headers,
- ...otherOptions,
- signal: controller.signal,
- })
- clearTimeout(id)
-
- if (!response.ok) return handleResponseError(response, requestId)
- return handleResponse(response, requestId)
- } catch (error) {
- return handleError(error, requestId)
- }
-}
diff --git a/apps/studio/lib/common/fetch/index.ts b/apps/studio/lib/common/fetch/index.ts
index e374cad9dc1..f476c3c02f4 100644
--- a/apps/studio/lib/common/fetch/index.ts
+++ b/apps/studio/lib/common/fetch/index.ts
@@ -9,7 +9,7 @@ export {
isResponseOk,
} from './base'
export { delete_ } from './delete'
-export { get, getWithTimeout } from './get'
+export { get } from './get'
export { head, headWithTimeout } from './head'
export { patch } from './patch'
export { post } from './post'