Skip to content

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

feat(content api): add error endpoint (#35941)

Charisaba0095bd748
diff --git a/apps/docs/app/api/graphql/__snapshots__/route.test.ts.snap b/apps/docs/app/api/graphql/__snapshots__/route.test.ts.snap
index c668a0b5208..5c0bac58a6a 100644
--- a/apps/docs/app/api/graphql/__snapshots__/route.test.ts.snap
+++ b/apps/docs/app/api/graphql/__snapshots__/route.test.ts.snap
@@ -131,6 +131,9 @@ type RootQueryType {
"""Search the Supabase docs for content matching a query string"""
searchDocs(query: String!, limit: Int): SearchResultCollection
+
+ """Get the details of an error code returned from a Supabase service"""
+ error(code: String!, service: Service!): Error
}
"""A collection of search results containing content from Supabase docs"""
@@ -149,5 +152,30 @@ type SearchResultCollection {
type SearchResultEdge {
"""The SearchResult at the end of the edge"""
node: SearchResult!
+}
+
+"""An error returned by a Supabase service"""
+type Error {
+ """
+ The unique code identifying the error. The code is stable, and can be used for string matching during error handling.
+ """
+ code: String!
+
+ """The Supabase service that returns this error."""
+ service: Service!
+
+ """The HTTP status code returned with this error."""
+ httpStatusCode: Int
+
+ """
+ A human-readable message describing the error. The message is not stable, and should not be used for string matching during error handling. Use the code instead.
+ """
+ message: String
+}
+
+enum Service {
+ AUTH
+ REALTIME
+ STORAGE
}"
`;
diff --git a/apps/docs/app/api/graphql/route.test.ts b/apps/docs/app/api/graphql/route.test.ts
index 8b464e23f9d..bcd6633e9bf 100644
--- a/apps/docs/app/api/graphql/route.test.ts
+++ b/apps/docs/app/api/graphql/route.test.ts
@@ -3,15 +3,11 @@ import { POST } from './route'
describe('/api/graphql basic error statuses', () => {
beforeAll(() => {
- vi.mock('server-only', () => {
- return {}
- })
vi.spyOn(console, 'error').mockImplementation(() => {})
})
afterAll(() => {
vi.restoreAllMocks()
- vi.doUnmock('server-only')
})
beforeEach(() => {
diff --git a/apps/docs/app/api/graphql/tests/errors.test.ts b/apps/docs/app/api/graphql/tests/errors.test.ts
new file mode 100644
index 00000000000..92972b850fb
--- /dev/null
+++ b/apps/docs/app/api/graphql/tests/errors.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it, vi } from 'vitest'
+import { POST } from '../route'
+
+describe('/api/graphql error', () => {
+ it('returns the error matching given error code and service', async () => {
+ const errorQuery = `
+ query {
+ error(code: "test_code", service: AUTH) {
+ code
+ service
+ httpStatusCode
+ message
+ }
+ }
+ `
+ const request = new Request('http://localhost/api/graphql', {
+ method: 'POST',
+ body: JSON.stringify({ query: errorQuery }),
+ })
+
+ const result = await POST(request)
+ const {
+ data: { error },
+ errors,
+ } = await result.json()
+
+ expect(errors).toBeUndefined()
+ expect(error.code).toBe('test_code')
+ expect(error.service).toBe('AUTH')
+ expect(error.httpStatusCode).toBe(500)
+ expect(error.message).toBe('This is a test error message')
+ })
+
+ it('returns error if no matching error exists', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+
+ const errorQuery = `
+ query {
+ error(code: "nonexistent_code", service: AUTH) {
+ code
+ service
+ httpStatusCode
+ message
+ }
+ }
+ `
+ const request = new Request('http://localhost/api/graphql', {
+ method: 'POST',
+ body: JSON.stringify({ query: errorQuery }),
+ })
+
+ const result = await POST(request)
+ const {
+ data: { error },
+ errors,
+ } = await result.json()
+
+ expect(error).toBe(null)
+ expect(errors).toHaveLength(1)
+ expect(errors[0].message).toMatch(/not found/i)
+
+ vi.restoreAllMocks()
+ })
+})
diff --git a/apps/docs/app/api/utils.ts b/apps/docs/app/api/utils.ts
index a2e87017713..949947abce5 100644
--- a/apps/docs/app/api/utils.ts
+++ b/apps/docs/app/api/utils.ts
@@ -45,6 +45,24 @@ export class InvalidRequestError<Details extends ObjectOrNever = never> extends
}
}
+export class NoDataError<Details extends ObjectOrNever = never> extends ApiError<Details> {
+ constructor(message: string, source?: unknown, details?: Details) {
+ super(`Data not found: ${message}`, source, details)
+ }
+
+ isPrivate() {
+ return false
+ }
+
+ isUserError() {
+ return true
+ }
+
+ statusCode() {
+ return 404
+ }
+}
+
export function convertUnknownToApiError(error: unknown): ApiError {
return new ApiError('Unknown error', error)
}
diff --git a/apps/docs/lib/supabase.ts b/apps/docs/lib/supabase.ts
index 3d3ab8820f8..7c46ef9c993 100644
--- a/apps/docs/lib/supabase.ts
+++ b/apps/docs/lib/supabase.ts
@@ -2,6 +2,7 @@ import { createClient, type SupabaseClient } from '@supabase/supabase-js'
import { type Database as DatabaseGenerated } from 'common'
type Database = {
+ content: DatabaseGenerated['content']
graphql_public: DatabaseGenerated['graphql_public']
public: {
Tables: DatabaseGenerated['public']['Tables']
diff --git a/apps/docs/resources/error/errorModel.ts b/apps/docs/resources/error/errorModel.ts
new file mode 100644
index 00000000000..ce9cb1d7c60
--- /dev/null
+++ b/apps/docs/resources/error/errorModel.ts
@@ -0,0 +1,74 @@
+import { ApiErrorGeneric, convertPostgrestToApiError, NoDataError } from '~/app/api/utils'
+import { Result } from '~/features/helpers.fn'
+import { supabase } from '~/lib/supabase'
+
+export const SERVICES = {
+ AUTH: {
+ value: 'AUTH',
+ },
+ REALTIME: {
+ value: 'REALTIME',
+ },
+ STORAGE: {
+ value: 'STORAGE',
+ },
+} as const
+
+type Service = keyof typeof SERVICES
+
+export class ErrorModel {
+ public code: string
+ public service: Service
+ public httpStatusCode?: number
+ public message?: string
+
+ constructor({
+ code,
+ service,
+ httpStatusCode: httpStatusCode,
+ message,
+ }: {
+ code: string
+ service: Service
+ httpStatusCode?: number
+ message?: string
+ }) {
+ this.code = code
+ this.service = service
+ this.httpStatusCode = httpStatusCode
+ this.message = message
+ }
+
+ static async loadSingleError({
+ code,
+ service,
+ }: {
+ code: string
+ service: Service
+ }): Promise<Result<ErrorModel, ApiErrorGeneric>> {
+ return new Result(
+ await supabase()
+ .schema('content')
+ .from('error')
+ .select('code, ...service(service:name), httpStatusCode:http_status_code, message')
+ .eq('code', code)
+ .eq('service.name', service)
+ .is('deleted_at', null)
+ .single<{
+ code: string
+ service: Service
+ httpStatusCode?: number
+ message?: string
+ }>()
+ )
+ .map((data) => {
+ return new ErrorModel(data)
+ })
+ .mapError((error) => {
+ if (error.code === 'PGRST116') {
+ return new NoDataError('Error for given code and service does not exist', error)
+ }
+ return convertPostgrestToApiError(error)
+ })
+ }
+}
diff --git a/apps/docs/resources/error/errorResolver.ts b/apps/docs/resources/error/errorResolver.ts
new file mode 100644
index 00000000000..ef79e2d887b
--- /dev/null
+++ b/apps/docs/resources/error/errorResolver.ts
@@ -0,0 +1,43 @@
+import { GraphQLError, GraphQLNonNull, GraphQLResolveInfo, GraphQLString } from 'graphql'
+import { type RootQueryTypeErrorArgs } from '~/__generated__/graphql'
+import { convertUnknownToApiError } from '~/app/api/utils'
+import { Result } from '~/features/helpers.fn'
+import { ErrorModel } from './errorModel'
+import {
+ GRAPHQL_FIELD_ERROR_GLOBAL,
+ GraphQLEnumTypeService,
+ GraphQLObjectTypeError,
+} from './errorSchema'
+
+async function resolveSingleError(
+ _parent: unknown,
+ args: RootQueryTypeErrorArgs,
+ _context: unknown,
+ _info: GraphQLResolveInfo
+): Promise<ErrorModel | GraphQLError> {
+ return (
+ await Result.tryCatchFlat(ErrorModel.loadSingleError, convertUnknownToApiError, args)
+ ).match(
+ (data) => data,
+ (error) => {
+ console.error(`Error resolving ${GRAPHQL_FIELD_ERROR_GLOBAL}:`, error)
+ return new GraphQLError(error.isPrivate() ? 'Internal Server Error' : error.message)
+ }
+ )
+}
+
+export const errorRoot = {
+ [GRAPHQL_FIELD_ERROR_GLOBAL]: {
+ description: 'Get the details of an error code returned from a Supabase service',
+ args: {
+ code: {
+ type: new GraphQLNonNull(GraphQLString),
+ },
+ service: {
+ type: new GraphQLNonNull(GraphQLEnumTypeService),
+ },
+ },
+ type: GraphQLObjectTypeError,
+ resolve: resolveSingleError,
+ },
+}
diff --git a/apps/docs/resources/error/errorSchema.ts b/apps/docs/resources/error/errorSchema.ts
new file mode 100644
index 00000000000..c752d705336
--- /dev/null
+++ b/apps/docs/resources/error/errorSchema.ts
@@ -0,0 +1,40 @@
+import {
+ GraphQLEnumType,
+ GraphQLInt,
+ GraphQLNonNull,
+ GraphQLObjectType,
+ GraphQLString,
+} from 'graphql'
+import { SERVICES } from './errorModel'
+
+export const GRAPHQL_FIELD_ERROR_GLOBAL = 'error' as const
+
+export const GraphQLEnumTypeService = new GraphQLEnumType({
+ name: 'Service',
+ values: SERVICES,
+})
+
+export const GraphQLObjectTypeError = new GraphQLObjectType({
+ name: 'Error',
+ description: 'An error returned by a Supabase service',
+ fields: {
+ code: {
+ type: new GraphQLNonNull(GraphQLString),
+ description:
+ 'The unique code identifying the error. The code is stable, and can be used for string matching during error handling.',
+ },
+ service: {
+ type: new GraphQLNonNull(GraphQLEnumTypeService),
+ description: 'The Supabase service that returns this error.',
+ },
+ httpStatusCode: {
+ type: GraphQLInt,
+ description: 'The HTTP status code returned with this error.',
+ },
+ message: {
+ type: GraphQLString,
+ description:
+ 'A human-readable message describing the error. The message is not stable, and should not be used for string matching during error handling. Use the code instead.',
+ },
+ },
+})
diff --git a/apps/docs/resources/rootSchema.ts b/apps/docs/resources/rootSchema.ts
index 5c543d1e79f..02ea9cc9697 100644
--- a/apps/docs/resources/rootSchema.ts
+++ b/apps/docs/resources/rootSchema.ts
@@ -6,6 +6,7 @@ import {
printSchema,
} from 'graphql'
import { RootQueryTypeResolvers } from '~/__generated__/graphql'
+import { errorRoot } from './error/errorResolver'
import { searchRoot } from './globalSearch/globalSearchResolver'
import { GraphQLObjectTypeGuide } from './guide/guideSchema'
import { GraphQLObjectTypeReferenceCLICommand } from './reference/referenceCLISchema'
@@ -35,6 +36,7 @@ export const rootGraphQLSchema = new GraphQLSchema({
fields: {
...introspectRoot,
...searchRoot,
+ ...errorRoot,
},
}),
types: [
diff --git a/apps/docs/vitest.config.ts b/apps/docs/vitest.config.ts
index b0047198db1..bbadb9591ec 100644
--- a/apps/docs/vitest.config.ts
+++ b/apps/docs/vitest.config.ts
@@ -1,9 +1,10 @@
-import { defineConfig } from 'vitest/config'
import tsconfigPaths from 'vite-tsconfig-paths'
+import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
exclude: ['examples/**/*', '**/node_modules/**'],
+ setupFiles: ['vitest.setup.ts'],
},
plugins: [tsconfigPaths({ root: import.meta.dirname })],
})
diff --git a/apps/docs/vitest.setup.ts b/apps/docs/vitest.setup.ts
new file mode 100644
index 00000000000..ef03c799e6a
--- /dev/null
+++ b/apps/docs/vitest.setup.ts
@@ -0,0 +1,24 @@
+import { afterAll, beforeAll, vi } from 'vitest'
+
+let oldEnv: NodeJS.ProcessEnv
+
+beforeAll(() => {
+ // Use local Supabase to run e2e tests
+ oldEnv = { ...process.env }
+ process.env = {
+ ...process.env,
+ NEXT_PUBLIC_SUPABASE_URL: 'http://localhost:54321',
+ NEXT_PUBLIC_SUPABASE_ANON_KEY:
+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0',
+ }
+
+ // Prevent errors about importing server-only modules from Client Components
+ vi.mock('server-only', () => {
+ return {}
+ })
+})
+
+afterAll(() => {
+ process.env = oldEnv
+ vi.doUnmock('server-only')
+})
diff --git a/packages/common/database-types.ts b/packages/common/database-types.ts
index 7941ad59978..8bdff5b8734 100644
--- a/packages/common/database-types.ts
+++ b/packages/common/database-types.ts
@@ -1,6 +1,98 @@
export type Json = string | number | boolean | null | { [key: string]: Json | undefined } | Json[]
export type Database = {
+ content: {
+ Tables: {
+ error: {
+ Row: {
+ code: string
+ created_at: string | null
+ deleted_at: string | null
+ http_status_code: number | null
+ message: string | null
+ service: string
+ updated_at: string | null
+ }
+ Insert: {
+ code: string
+ created_at?: string | null
+ deleted_at?: string | null
+ http_status_code?: number | null
+ message?: string | null
+ service: string
+ updated_at?: string | null
+ }
+ Update: {
+ code?: string
+ created_at?: string | null
+ deleted_at?: string | null
+ http_status_code?: number | null
+ message?: string | null
+ service?: string
+ updated_at?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: 'error_service_fkey'
+ columns: ['service']
+ isOneToOne: false
+ referencedRelation: 'service'
+ referencedColumns: ['id']
+ },
+ ]
+ }
+ service: {
+ Row: {
+ created_at: string | null
+ deleted_at: string | null
+ id: string
+ name: string
+ updated_at: string | null
+ }
+ Insert: {
+ created_at?: string | null
+ deleted_at?: string | null
+ id?: string
+ name: string
+ updated_at?: string | null
+ }
+ Update: {
+ created_at?: string | null
+ deleted_at?: string | null
+ id?: string
+ name?: string
+ updated_at?: string | null
+ }
+ Relationships: []
+ }
+ }
+ Views: {
+ [_ in never]: never
+ }
+ Functions: {
+ delete_error_codes_except: {
+ Args: {
+ skip_codes: Json
+ }
+ Returns: undefined
+ }
+ update_error_code: {
+ Args: {
+ code: string
+ service: string
+ http_status_code?: number
+ message?: string
+ }
+ Returns: boolean
+ }
+ }
+ Enums: {
+ [_ in never]: never
+ }
+ CompositeTypes: {
+ [_ in never]: never
+ }
+ }
graphql_public: {
Tables: {
[_ in never]: never
diff --git a/supabase/seed.sql b/supabase/seed.sql
index 702adcfcd90..fa76ef7fb1e 100644
--- a/supabase/seed.sql
+++ b/supabase/seed.sql
@@ -6,3 +6,13 @@ values
('Singapore', 'Singapore', 'lw12', now(), true);
insert into public.launch_weeks (id) values ('lw14');
+
+-- Insert mock error codes for testing
+insert into content.error (code, service, http_status_code, message)
+values
+ (
+ 'test_code',
+ (select id from content.service where name = 'AUTH'),
+ 500,
+ 'This is a test error message'
+ );