The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Chore/more refactoring of data fetchers methods (#33553)
Joshen Lime539b892a691
diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagement.schema.ts b/apps/studio/components/interfaces/DiskManagement/DiskManagement.schema.tsindex 027d44fb0d7..2c6a8990542 100644--- a/apps/studio/components/interfaces/DiskManagement/DiskManagement.schema.ts+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagement.schema.ts@@ -14,6 +14,7 @@ const baseSchema = z.object({storageType: z.enum(['io2', 'gp3']).describe('Type of storage: io2 or gp3'),totalSize: z.number()+ .int('Value must be an integer').min(8, { message: 'Allocated disk size must be at least 8 GB.' }).describe('Allocated disk size in GB'),provisionedIOPS: z.number().describe('Provisioned IOPS for storage type'),diff --git a/apps/studio/data/config/project-disk-resize-mutation.ts b/apps/studio/data/config/project-disk-resize-mutation.tsindex 1118c9286f2..29b63ca358c 100644--- a/apps/studio/data/config/project-disk-resize-mutation.ts+++ b/apps/studio/data/config/project-disk-resize-mutation.ts@@ -1,8 +1,7 @@import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'import { toast } from 'sonner'-import { post } from 'lib/common/fetch'-import { API_URL } from 'lib/constants'+import { handleError, post } from 'data/fetchers'import type { ResponseError } from 'types'import { usageKeys } from '../usage/keys'@@ -11,22 +10,17 @@ export type ProjectDiskResizeVariables = {volumeSize: number}-export type ProjectDiskResizeResponse = {- error?: any-}-export async function resizeProjectDisk({ projectRef, volumeSize }: ProjectDiskResizeVariables) {if (!projectRef) throw new Error('projectRef is required')const payload = { volume_size_gb: volumeSize }- const response = (await post(- `${API_URL}/projects/${projectRef}/resize`,- payload- )) as ProjectDiskResizeResponse- if (response.error) throw response.error-- return response+ const { data, error } = await post('/platform/projects/{ref}/resize', {+ params: { path: { ref: projectRef } },+ body: payload,+ })+ if (error) handleError(error)+ return data}type ProjectDiskResizeData = Awaited<ReturnType<typeof resizeProjectDisk>>diff --git a/apps/studio/data/config/project-postgrest-config-query.ts b/apps/studio/data/config/project-postgrest-config-query.tsindex 58b89563145..9e78093329e 100644--- a/apps/studio/data/config/project-postgrest-config-query.ts+++ b/apps/studio/data/config/project-postgrest-config-query.ts@@ -1,39 +1,32 @@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 { ResponseError } from 'types'+import { configKeys } from './keys'export type ProjectPostgrestConfigVariables = {projectRef?: string}-export type ProjectPostgrestConfigResponse = {- max_rows: number- role_claim_key: string- db_schema: string- db_anon_role: string- db_extra_search_path: string+type PostgrestConfigResponse = components['schemas']['PostgrestConfigResponse'] & {db_pool: number | null- jwt_secret: string}export async function getProjectPostgrestConfig({ projectRef }: ProjectPostgrestConfigVariables,signal?: AbortSignal) {- if (!projectRef) {- throw new Error('projectRef is required')- }+ if (!projectRef) throw new Error('projectRef is required')- const response = await get(`${API_URL}/projects/${projectRef}/config/postgrest`, {+ const { data, error } = await get('/platform/projects/{ref}/config/postgrest', {+ params: { path: { ref: projectRef } },signal,})- if (response.error) {- throw response.error- }-- return response as ProjectPostgrestConfigResponse+ if (error) handleError(error)+ // [Joshen] Not sure why but db_pool isn't part of the API typing+ // https://github.com/supabase/infrastructure/blob/develop/api/src/routes/platform/projects/ref/config/postgrest.dto.ts#L6+ return data as unknown as PostgrestConfigResponse}export type ProjectPostgrestConfigData = Awaited<ReturnType<typeof getProjectPostgrestConfig>>diff --git a/apps/studio/data/config/project-postgrest-config-update-mutation.ts b/apps/studio/data/config/project-postgrest-config-update-mutation.tsindex 89dcde2befd..7cc3fafc694 100644--- a/apps/studio/data/config/project-postgrest-config-update-mutation.ts+++ b/apps/studio/data/config/project-postgrest-config-update-mutation.ts@@ -1,8 +1,8 @@import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'import { toast } from 'sonner'-import { patch } from 'lib/common/fetch'-import { API_URL } from 'lib/constants'+import { components } from 'api-types'+import { handleError, patch } from 'data/fetchers'import type { ResponseError } from 'types'import { configKeys } from './keys'@@ -14,6 +14,8 @@ export type ProjectPostgrestConfigUpdateVariables = {dbPool: number | null}+type UpdatePostgrestConfigResponse = components['schemas']['UpdatePostgrestConfigBody']+export async function updateProjectPostgrestConfig({projectRef,dbSchema,@@ -21,15 +23,20 @@ export async function updateProjectPostgrestConfig({dbExtraSearchPath,dbPool,}: ProjectPostgrestConfigUpdateVariables) {- const response = await patch(`${API_URL}/projects/${projectRef}/config/postgrest`, {+ const payload: UpdatePostgrestConfigResponse = {db_schema: dbSchema,max_rows: maxRows,db_extra_search_path: dbExtraSearchPath,- db_pool: dbPool,+ }+ if (dbPool) payload.db_pool = dbPool++ const { data, error } = await patch('/platform/projects/{ref}/config/postgrest', {+ params: { path: { ref: projectRef } },+ body: payload,})- if (response.error) throw response.error- return response+ if (error) handleError(error)+ return data}type ProjectPostgrestConfigUpdateData = Awaited<ReturnType<typeof updateProjectPostgrestConfig>>diff --git a/apps/studio/data/feedback/exit-survey-send.ts b/apps/studio/data/feedback/exit-survey-send.tsindex ada87365ab4..c8b8546c9b7 100644--- a/apps/studio/data/feedback/exit-survey-send.ts+++ b/apps/studio/data/feedback/exit-survey-send.ts@@ -1,8 +1,7 @@import { useMutation, UseMutationOptions } from '@tanstack/react-query'import { toast } from 'sonner'-import { post } from 'lib/common/fetch'-import { API_URL } from 'lib/constants'+import { handleError, post } from 'data/fetchers'import type { ResponseError } from 'types'export type SendDowngradeFeedbackVariables = {@@ -20,15 +19,17 @@ export async function sendDowngradeFeedback({message,exitAction,}: SendDowngradeFeedbackVariables) {- const response = await post(`${API_URL}/feedback/downgrade`, {- ...(projectRef !== undefined && { projectRef }),- ...(orgSlug !== undefined && { orgSlug }),- reasons,- additionalFeedback: message,- exitAction,+ const { data, error } = await post('/platform/feedback/downgrade', {+ body: {+ ...(projectRef !== undefined && { projectRef }),+ ...(orgSlug !== undefined && { orgSlug }),+ reasons,+ additionalFeedback: message,+ exitAction,+ },})- if (response.error) throw response.error- return response+ if (error) handleError(error)+ return data}type SendDowngradeFeedbackData = Awaited<ReturnType<typeof sendDowngradeFeedback>>diff --git a/apps/studio/data/feedback/upgrade-survey-send.ts b/apps/studio/data/feedback/upgrade-survey-send.tsindex bf41f599e1f..282bdcdf258 100644--- a/apps/studio/data/feedback/upgrade-survey-send.ts+++ b/apps/studio/data/feedback/upgrade-survey-send.ts@@ -1,7 +1,6 @@import { useMutation, UseMutationOptions } from '@tanstack/react-query'import { toast } from 'sonner'-// import { post } from 'lib/common/fetch'import { handleError, post } from 'data/fetchers'import type { ResponseError } from 'types'diff --git a/apps/studio/data/organizations/free-project-limit-check-query.ts b/apps/studio/data/organizations/free-project-limit-check-query.tsindex 8f7a46f9a90..63e4b89b79f 100644--- a/apps/studio/data/organizations/free-project-limit-check-query.ts+++ b/apps/studio/data/organizations/free-project-limit-check-query.ts@@ -1,39 +1,31 @@import { useQuery, UseQueryOptions } from '@tanstack/react-query'-import { get } from 'lib/common/fetch'-import { API_URL } from 'lib/constants'++import { components } from 'api-types'+import { get, handleError } from 'data/fetchers'import { organizationKeys } from './keys'-export type MemberWithFreeProjectLimit = {- free_project_limit: number- primary_email: string- username: string-}+export type MemberWithFreeProjectLimit = components['schemas']['MemberWithFreeProjectLimit']export type FreeProjectLimitCheckVariables = {slug?: string}-export type FreeProjectLimitCheckResponse = MemberWithFreeProjectLimit[]-export async function getFreeProjectLimitCheck({ slug }: FreeProjectLimitCheckVariables,signal?: AbortSignal) {- if (!slug) {- throw new Error('slug is required')- }+ if (!slug) throw new Error('slug is required')- const response = await get(- `${API_URL}/organizations/${slug}/members/reached-free-project-limit`,+ const { data, error } = await get(+ '/platform/organizations/{slug}/members/reached-free-project-limit',{+ params: { path: { slug } },signal,})- if (response.error) {- throw response.error- }- return response as FreeProjectLimitCheckResponse+ if (error) handleError(error)+ return data}export type FreeProjectLimitCheckData = Awaited<ReturnType<typeof getFreeProjectLimitCheck>>diff --git a/apps/studio/data/organizations/organization-audit-logs-query.ts b/apps/studio/data/organizations/organization-audit-logs-query.tsindex 0c3a63c76a7..67df5e1fa9f 100644--- a/apps/studio/data/organizations/organization-audit-logs-query.ts+++ b/apps/studio/data/organizations/organization-audit-logs-query.ts@@ -1,8 +1,7 @@import { useQuery, UseQueryOptions } from '@tanstack/react-query'import dayjs from 'dayjs'-import { get } from 'lib/common/fetch'-import { API_URL } from 'lib/constants'+import { get, handleError } from 'data/fetchers'import type { ResponseError } from 'types'import { organizationKeys } from './keys'@@ -40,21 +39,22 @@ export type OrganizationAuditLogsVariables = {slug?: stringiso_timestamp_start?: stringiso_timestamp_end?: string- project_refs?: string // Comma-separated}export async function getOrganizationAuditLogs(- { slug, iso_timestamp_start, iso_timestamp_end, project_refs }: OrganizationAuditLogsVariables,+ { slug, iso_timestamp_start, iso_timestamp_end }: OrganizationAuditLogsVariables,signal?: AbortSignal) {if (!slug) throw new Error('slug is required')- const response = await get(- `${API_URL}/organizations/${slug}/audit?iso_timestamp_start=${iso_timestamp_start}&iso_timestamp_end=${iso_timestamp_end}`,- { signal }- )- if (response.error) throw response.error- return response as OrganizationAuditLogsResponse+ const { data, error } = await get('/platform/organizations/{slug}/audit', {+ params: { path: { slug }, query: { iso_timestamp_start, iso_timestamp_end } },+ signal,+ })++ if (error) handleError(error)+ // [Joshen] API doesn't generate types for each audit log properly+ return data as unknown as OrganizationAuditLogsResponse}export type OrganizationAuditLogsData = Awaited<ReturnType<typeof getOrganizationAuditLogs>>diff --git a/apps/studio/data/organizations/organization-member-delete-mutation.ts b/apps/studio/data/organizations/organization-member-delete-mutation.tsindex abb41d19dc3..1f9e013908e 100644--- a/apps/studio/data/organizations/organization-member-delete-mutation.ts+++ b/apps/studio/data/organizations/organization-member-delete-mutation.ts@@ -1,8 +1,7 @@import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'import { toast } from 'sonner'-import { delete_ } from 'lib/common/fetch'-import { API_URL } from 'lib/constants'+import { del, handleError } from 'data/fetchers'import type { ResponseError } from 'types'import { organizationKeys } from './keys'@@ -15,9 +14,11 @@ export async function deleteOrganizationMember({slug,gotrueId,}: OrganizationMemberDeleteVariables) {- const response = await delete_(`${API_URL}/organizations/${slug}/members/${gotrueId}`)- if (response.error) throw response.error- return response+ const { data, error } = await del('/platform/organizations/{slug}/members/{gotrue_id}', {+ params: { path: { slug, gotrue_id: gotrueId } },+ })+ if (error) handleError(error)+ return data}type OrganizationMemberDeleteData = Awaited<ReturnType<typeof deleteOrganizationMember>>diff --git a/apps/studio/data/projects/project-update-mutation.ts b/apps/studio/data/projects/project-update-mutation.tsindex 5ac17aa3a4e..68eebe38ebf 100644--- a/apps/studio/data/projects/project-update-mutation.ts+++ b/apps/studio/data/projects/project-update-mutation.ts@@ -1,8 +1,7 @@import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'import { toast } from 'sonner'-import { patch } from 'lib/common/fetch'-import { API_URL } from 'lib/constants'+import { handleError, patch } from 'data/fetchers'import type { ResponseError } from 'types'import { projectKeys } from './keys'@@ -18,9 +17,12 @@ export type ProjectUpdateResponse = {}export async function updateProject({ ref, name }: ProjectUpdateVariables) {- const response = await patch(`${API_URL}/projects/${ref}`, { name })- if (response.error) throw response.error- return response as ProjectUpdateResponse+ const { data, error } = await patch('/platform/projects/{ref}', {+ params: { path: { ref } },+ body: { name },+ })+ if (error) handleError(error)+ return data}type ProjectUpdateData = Awaited<ReturnType<typeof updateProject>>diff --git a/apps/studio/data/service-status/postgres-service-status-query.ts b/apps/studio/data/service-status/postgres-service-status-query.tsindex 0ba96d5e079..b2343660a69 100644--- a/apps/studio/data/service-status/postgres-service-status-query.ts+++ b/apps/studio/data/service-status/postgres-service-status-query.ts@@ -1,9 +1,8 @@import { useQuery, UseQueryOptions } from '@tanstack/react-query'-import { post } from 'lib/common/fetch'+import { handleError, post } from 'data/fetchers'import type { ResponseError } from 'types'import { serviceStatusKeys } from './keys'-import { API_URL } from 'lib/constants'export type PostgresServiceStatusVariables = {projectRef?: string@@ -20,14 +19,20 @@ export async function getPostgresServiceStatus(let headers = new Headers()headers.set('x-connection-encrypted', connectionString)- const response = await post(- `${API_URL}/pg-meta/${projectRef}/query?key=service_status`,- { query: 'select 1' },- { headers: Object.fromEntries(headers), signal }- )-- if (response.error) throw response.error- return response.error === undefined+ const { error } = await post('/platform/pg-meta/{ref}/query', {+ params: {+ header: { 'x-connection-encrypted': connectionString! },+ path: { ref: projectRef },+ // @ts-expect-error Intentional key for easier reference of query in the network tab+ query: { key: 'service_status' },+ },+ body: { query: 'select 1' },+ headers,+ signal,+ })++ if (error) handleError(error)+ return error === undefined}export type PostgresServiceStatusData = Awaited<ReturnType<typeof getPostgresServiceStatus>>diff --git a/apps/studio/data/storage/bucket-object-download-mutation.ts b/apps/studio/data/storage/bucket-object-download-mutation.tsindex 81d5992d219..0c790f11353 100644--- a/apps/studio/data/storage/bucket-object-download-mutation.ts+++ b/apps/studio/data/storage/bucket-object-download-mutation.ts@@ -3,7 +3,7 @@ import { toast } from 'sonner'import { components } from 'data/api'import { post } from 'lib/common/fetch'-import { API_URL } from 'lib/constants'+import { API_URL, IS_PLATFORM } from 'lib/constants'import { ResponseError } from 'types'type DownloadBucketObjectParams = {@@ -18,9 +18,10 @@ export const downloadBucketObject = async () => {if (!bucketId) throw new Error('bucketId is required')- // has to use lib/common/fetch post because the other post doesn't support wrapping blobs+ // [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 happeningconst response = await post(- `${API_URL}/storage/${projectRef}/buckets/${bucketId}/objects/download`,+ `${API_URL}${IS_PLATFORM ? '' : '/platform'}/storage/${projectRef}/buckets/${bucketId}/objects/download`,{path,options,diff --git a/apps/studio/lib/common/fetch/get.ts b/apps/studio/lib/common/fetch/get.tsindex 941c5eb4b58..0d9382c9529 100644--- a/apps/studio/lib/common/fetch/get.ts+++ b/apps/studio/lib/common/fetch/get.ts@@ -1,9 +1,9 @@-import { handleError, handleResponse, handleResponseError, constructHeaders } from './base'-import { uuidv4 } from '../../helpers'import type { SupaResponse } from 'types/base'+import { uuidv4 } from '../../helpers'+import { constructHeaders, handleError, handleResponse, handleResponseError } from './base'/**- * @deprecated please use get method from data/fetchers instead+ * @deprecated Please use get method from data/fetchers instead, unless making requests to an external URL*/export async function get<T = any>(url: string,diff --git a/apps/studio/lib/common/fetch/post.ts b/apps/studio/lib/common/fetch/post.tsindex 32e717e54a7..9eea5771411 100644--- a/apps/studio/lib/common/fetch/post.ts+++ b/apps/studio/lib/common/fetch/post.ts@@ -1,9 +1,11 @@-import { handleError, handleResponse, handleResponseError, constructHeaders } from './base'import { uuidv4 } from 'lib/helpers'import type { SupaResponse } from 'types/base'+import { constructHeaders, handleError, handleResponse, handleResponseError } from './base'/**- * @deprecated please use post method from data/fetchers instead+ * @deprecated Please use post method from data/fetchers instead+ *+ * Exception for bucket-object-download-mutation as openapi-fetch doesn't support octet-stream responses*/export async function post<T = any>(url: string,diff --git a/apps/studio/lib/password-strength.ts b/apps/studio/lib/password-strength.tsindex 2d4defad5c9..cf813807e54 100644--- a/apps/studio/lib/password-strength.ts+++ b/apps/studio/lib/password-strength.ts@@ -1,6 +1,7 @@-import { post } from 'lib/common/fetch'-import { API_URL, DEFAULT_MINIMUM_PASSWORD_STRENGTH, PASSWORD_STRENGTH } from 'lib/constants'+import { post as post_ } from 'data/fetchers'+import { DEFAULT_MINIMUM_PASSWORD_STRENGTH, PASSWORD_STRENGTH } from 'lib/constants'import { toast } from 'sonner'+import { ResponseError } from 'types'export default async function passwordStrength(value: string) {let message: string = ''@@ -12,10 +13,11 @@ export default async function passwordStrength(value: string) {message = `${PASSWORD_STRENGTH[0]} Maximum length of password exceeded`warning = `Password should be less than 100 characters`} else {- // [Joshen] Unable to use RQ atm due to our Jest tests being in JS- const response = await post(`${API_URL}/profile/password-check`, { password: value })- if (!response.error) {- const { result } = response+ const { data, error } = await post_('/platform/profile/password-check', {+ body: { password: value },+ })+ if (!error) {+ const { result } = dataconst resultScore = result?.score ?? 0const score = (PASSWORD_STRENGTH as any)[resultScore]@@ -33,7 +35,7 @@ export default async function passwordStrength(value: string) {} You need a stronger password.`}} else {- toast.error(`Failed to check password strength: ${response.error.message}`)+ toast.error(`Failed to check password strength: ${(error as ResponseError).message}`)}}}