The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
refactor: isResponseOk() helper type guard
Greg Richardsondf17fb21d7f6
diff --git a/studio/data/content/content-create-mutation.ts b/studio/data/content/content-create-mutation.tsindex d6646f3d9e1..1428c78ee65 100644--- a/studio/data/content/content-create-mutation.ts+++ b/studio/data/content/content-create-mutation.ts@@ -1,5 +1,5 @@import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'-import { post } from 'lib/common/fetch'+import { isResponseOk, post } from 'lib/common/fetch'import { API_URL } from 'lib/constants'import { UserContent } from 'types'import { contentKeys } from './keys'@@ -17,7 +17,7 @@ export async function createContent(signal,})- if ('error' in response) {+ if (!isResponseOk(response)) {throw response.error}diff --git a/studio/data/content/content-delete-mutation.ts b/studio/data/content/content-delete-mutation.tsindex c382590edc7..2072d0c4c27 100644--- a/studio/data/content/content-delete-mutation.ts+++ b/studio/data/content/content-delete-mutation.ts@@ -1,5 +1,5 @@import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'-import { delete_ } from 'lib/common/fetch'+import { delete_, isResponseOk } from 'lib/common/fetch'import { API_URL } from 'lib/constants'import { UserContent } from 'types'import { contentKeys } from './keys'@@ -16,7 +16,7 @@ export async function deleteContent({ signal })- if ('error' in response) {+ if (!isResponseOk(response)) {throw response.error}diff --git a/studio/data/content/content-update-mutation.ts b/studio/data/content/content-update-mutation.tsindex 7c87ba22d94..7089fee27f5 100644--- a/studio/data/content/content-update-mutation.ts+++ b/studio/data/content/content-update-mutation.ts@@ -1,5 +1,5 @@import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'-import { patch } from 'lib/common/fetch'+import { isResponseOk, patch } from 'lib/common/fetch'import { API_URL } from 'lib/constants'import { UserContent } from 'types'import { contentKeys } from './keys'@@ -19,7 +19,7 @@ export async function updateContent(content,{ signal })- if ('error' in created) {+ if (!isResponseOk(created)) {throw created.error}diff --git a/studio/data/integrations/integrations-vercel-installed-connection-delete-mutation.ts b/studio/data/integrations/integrations-vercel-installed-connection-delete-mutation.tsindex aebf6012ef5..3601e55237a 100644--- a/studio/data/integrations/integrations-vercel-installed-connection-delete-mutation.ts+++ b/studio/data/integrations/integrations-vercel-installed-connection-delete-mutation.ts@@ -1,5 +1,5 @@import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'-import { delete_ } from 'lib/common/fetch'+import { delete_, isResponseOk } from 'lib/common/fetch'import { API_URL } from 'lib/constants'import { UserContent } from 'types'import { integrationKeys } from './keys'@@ -24,7 +24,7 @@ export async function deleteConnection({ signal })- if ('error' in response) {+ if (!isResponseOk(response)) {throw response.error}diff --git a/studio/data/subscriptions/org-subscription-update-mutation.ts b/studio/data/subscriptions/org-subscription-update-mutation.tsindex 9c032b3c776..04c47ab8395 100644--- a/studio/data/subscriptions/org-subscription-update-mutation.ts+++ b/studio/data/subscriptions/org-subscription-update-mutation.ts@@ -1,5 +1,5 @@import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'-import { put } from 'lib/common/fetch'+import { isResponseOk, put } from 'lib/common/fetch'import { API_URL } from 'lib/constants'import { subscriptionKeys } from './keys'import { SupaResponse } from 'types/base'@@ -29,7 +29,10 @@ export async function updateOrgSubscription({if (paymentMethod !== undefined) payload.payment_method = paymentMethodconst response = await put<void>(`${API_URL}/organizations/${slug}/billing/subscription`, payload)- if (typeof response === 'object' && response !== null && 'error' in response) throw response.error+ if (!isResponseOk(response)) {+ throw response.error+ }+return response}diff --git a/studio/hooks/analytics/useLogsPreview.tsx b/studio/hooks/analytics/useLogsPreview.tsxindex 9846b4dec53..e7fa3b2d317 100644--- a/studio/hooks/analytics/useLogsPreview.tsx+++ b/studio/hooks/analytics/useLogsPreview.tsx@@ -17,7 +17,7 @@ import {} from 'components/interfaces/Settings/Logs'import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'import { API_URL } from 'lib/constants'-import { get } from 'lib/common/fetch'+import { get, isResponseOk } from 'lib/common/fetch'import dayjs from 'dayjs'import useFillTimeseriesSorted from './useFillTimeseriesSorted'import useTimeseriesUnixToIso from './useTimeseriesUnixToIso'@@ -86,7 +86,7 @@ function useLogsPreview({refetchOnWindowFocus: false,getNextPageParam(lastPage) {- if ('error' in lastPage || (lastPage?.result?.length ?? 0) === 0) {+ if (!isResponseOk(lastPage) || (lastPage.result?.length ?? 0) === 0) {return undefined}const len = lastPage.result.length@@ -121,7 +121,7 @@ function useLogsPreview(})- const newCount = countData && !('error' in countData) ? countData.result?.[0]?.count ?? 0 : 0+ const newCount = isResponseOk(countData) ? countData.result?.[0]?.count ?? 0 : 0// chart data@@ -155,7 +155,7 @@ function useLogsPreview(let error: null | string | object = rqError ? (rqError as any).message : nulldata?.pages.forEach((response) => {- if (!('error' in response) && !error && response?.result) {+ if (isResponseOk(response) && response.result) {logData = [...logData, ...response.result]}if (!error && response && response.error) {@@ -177,7 +177,7 @@ function useLogsPreview(}const normalizedEventChartData = useTimeseriesUnixToIso(- (eventChartResponse && !('error' in eventChartResponse) && eventChartResponse.result) || [],+ (isResponseOk(eventChartResponse) && eventChartResponse.result) || [],'timestamp')diff --git a/studio/hooks/analytics/useLogsQuery.tsx b/studio/hooks/analytics/useLogsQuery.tsxindex bfd6da5ba61..e0b0516d27c 100644--- a/studio/hooks/analytics/useLogsQuery.tsx+++ b/studio/hooks/analytics/useLogsQuery.tsx@@ -7,7 +7,7 @@ import {import { Dispatch, SetStateAction, useState } from 'react'import { LogsEndpointParams, Logs, LogData } from 'components/interfaces/Settings/Logs/Logs.types'import { API_URL } from 'lib/constants'-import { get } from 'lib/common/fetch'+import { get, isResponseOk } from 'lib/common/fetch'export interface LogsQueryHook {params: LogsEndpointParamsisLoading: boolean@@ -68,7 +68,7 @@ const useLogsQuery = (return {params,isLoading: (enabled && isLoading) || isRefetching,- logData: data && !('error' in data) && data.result ? data?.result : [],+ logData: isResponseOk(data) && data.result ? data.result : [],error,changeQuery,runQuery: () => refetch(),diff --git a/studio/lib/api/apiWrapper.ts b/studio/lib/api/apiWrapper.tsindex 9542bd88d68..4b9008a09c3 100644--- a/studio/lib/api/apiWrapper.ts+++ b/studio/lib/api/apiWrapper.ts@@ -1,4 +1,5 @@import { withSentry } from '@sentry/nextjs'+import { isResponseOk } from 'lib/common/fetch'import { NextApiHandler, NextApiRequest, NextApiResponse } from 'next'import { IS_PLATFORM } from '../constants'import { apiAuthenticate } from './apiAuthenticate'@@ -17,7 +18,7 @@ export default async function apiWrapper(if (IS_PLATFORM && withAuth) {const response = await apiAuthenticate(req, res)- if ('error' in response) {+ if (!isResponseOk(response)) {return res.status(401).json({error: {message: `Unauthorized: ${response.error.message}`,diff --git a/studio/lib/common/fetch/base.ts b/studio/lib/common/fetch/base.tsindex 7acd51d1dae..e0ed4805618 100644--- a/studio/lib/common/fetch/base.ts+++ b/studio/lib/common/fetch/base.ts@@ -113,3 +113,7 @@ export async function constructHeaders(requestId: string, optionHeaders?: { [proreturn headers}++export function isResponseOk<T>(response: SupaResponse<T> | undefined): response is T {+ return !!response && !(typeof response === 'object' && 'error' in response)+}diff --git a/studio/lib/integration-utils.ts b/studio/lib/integration-utils.tsindex c6013df73b5..976b5af7942 100644--- a/studio/lib/integration-utils.ts+++ b/studio/lib/integration-utils.ts@@ -1,5 +1,6 @@import { SupaResponse } from 'types'import { Integration } from 'data/integrations/integrations.types'+import { isResponseOk } from './common/fetch'async function fetchGitHub<T = any>(url: string, responseJson = true): Promise<SupaResponse<T>> {const response = await fetch(url)@@ -54,11 +55,11 @@ export async function getInitialMigrationSQLFromGitHubRepo(fetchGitHub<File[]>(migrationsFolderUrl),])- if ('error' in supabaseFilesResponse) {+ if (!isResponseOk(supabaseFilesResponse)) {console.warn(`Failed to fetch supabase files from GitHub: ${supabaseFilesResponse.error}`)return null}- if ('error' in migrationFilesResponse) {+ if (!isResponseOk(migrationFilesResponse)) {console.warn(`Failed to fetch migration files from GitHub: ${migrationFilesResponse.error}`)return null}@@ -79,11 +80,8 @@ export async function getInitialMigrationSQLFromGitHubRepo(...migrationFileDownloadUrlPromises,])- const migrations = migrationFileResponses- .filter((response) => !(typeof response === 'object' && 'error' in response))- .join(';')- const seed =- typeof seedFileResponse === 'object' && 'error' in seedFileResponse ? '' : seedFileResponse+ const migrations = migrationFileResponses.filter((response) => isResponseOk(response)).join(';')+ const seed = isResponseOk(seedFileResponse) ? seedFileResponse : ''const migrationsTableSql = /* SQL */ `create schema if not exists supabase_migrations;@@ -94,7 +92,7 @@ export async function getInitialMigrationSQLFromGitHubRepo();${sortedFiles.map((file, i) => {const migration = migrationFileResponses[i]- if (!migration || (typeof migration === 'object' && 'error' in migration)) return ''+ if (!isResponseOk(migration)) return ''const version = file.name.split('_')[0]const statements = JSON.stringify(diff --git a/studio/stores/common/PostgresMetaInterface.ts b/studio/stores/common/PostgresMetaInterface.tsindex e12ace8b098..903d840821f 100644--- a/studio/stores/common/PostgresMetaInterface.ts+++ b/studio/stores/common/PostgresMetaInterface.ts@@ -1,5 +1,5 @@import { action, computed, makeObservable, observable } from 'mobx'-import { get, patch, post, delete_ } from 'lib/common/fetch'+import { get, patch, post, delete_, isResponseOk } from 'lib/common/fetch'import { keyBy } from 'lodash'import { IRootStore } from '../RootStore'import { ResponseError } from 'types'@@ -95,7 +95,7 @@ export default class PostgresMetaInterface<T> implements IPostgresMetaInterface<async fetchData() {const headers = { 'Content-Type': 'application/json', ...this.headers }const response = await get<T[]>(this.url, { headers })- if ('error' in response) {+ if (!isResponseOk(response)) {throw response.error}@@ -215,7 +215,7 @@ export default class PostgresMetaInterface<T> implements IPostgresMetaInterface<const headers = { 'Content-Type': 'application/json', ...this.headers }const url = `${this.url}?id=${id}`const response = await patch<T>(url, payload, { headers })- if (response && typeof response === 'object' && 'error' in response) {+ if (!isResponseOk(response)) {throw response.error}@@ -231,7 +231,7 @@ export default class PostgresMetaInterface<T> implements IPostgresMetaInterface<const headers = { 'Content-Type': 'application/json', ...this.headers }const url = cascade ? `${this.url}?id=${id}&cascade=${cascade}` : `${this.url}?id=${id}`const response = await delete_<T>(url, {}, { headers })- if (response && typeof response === 'object' && 'error' in response) {+ if (!isResponseOk(response)) {throw response.error}diff --git a/studio/stores/pgmeta/OpenApiStore.ts b/studio/stores/pgmeta/OpenApiStore.tsindex 30fed0a6f81..08cf0e505da 100644--- a/studio/stores/pgmeta/OpenApiStore.ts+++ b/studio/stores/pgmeta/OpenApiStore.ts@@ -1,5 +1,5 @@import { makeAutoObservable } from 'mobx'-import { get } from 'lib/common/fetch'+import { get, isResponseOk } from 'lib/common/fetch'import { IRootStore } from '../RootStore'import { OpenAPIV2 } from 'openapi-types'@@ -53,7 +53,7 @@ export default class OpenApiStore implements IOpenApiStore {async fetchData() {const response = await get<OpenAPIV2.Document>(this.url)- if ('error' in response) {+ if (!isResponseOk(response)) {throw response.error}diff --git a/studio/stores/project/ProjectContentStore.ts b/studio/stores/project/ProjectContentStore.tsindex c567458647f..dda44eaca6f 100644--- a/studio/stores/project/ProjectContentStore.ts+++ b/studio/stores/project/ProjectContentStore.ts@@ -2,7 +2,7 @@ import { makeAutoObservable } from 'mobx'import { keyBy } from 'lodash'import { uuidv4 } from 'lib/helpers'-import { get, post, patch, delete_ } from 'lib/common/fetch'+import { get, post, patch, delete_, isResponseOk } from 'lib/common/fetch'import { LogSqlSnippets, UserContent, UserContentMap } from 'types'import { IRootStore } from '../RootStore'import { API_URL } from 'lib/constants'@@ -268,7 +268,7 @@ export default class ProjectContentStore implements IProjectContentStore {'Content-Type': 'application/json',}const created = await post<UserContent>(this.baseUrl, payload, { headers })- if ('error' in created) {+ if (!isResponseOk(created)) {throw created.error}@@ -327,7 +327,7 @@ export default class ProjectContentStore implements IProjectContentStore {const url = `${this.baseUrl}?id=${id}`const updated = await patch<UserContent[]>(url, payload, { headers })- if ('error' in updated) {+ if (!isResponseOk(updated)) {throw updated.error}