Skip to content

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

fix (content api): return graphql-spec compliant error (#35202)

Charisca1cd24a0797
diff --git a/apps/docs/app/api/graphql/route.test.ts b/apps/docs/app/api/graphql/route.test.ts
index 77d12a09ac4..c60bd1d9a62 100644
--- a/apps/docs/app/api/graphql/route.test.ts
+++ b/apps/docs/app/api/graphql/route.test.ts
@@ -7,39 +7,44 @@ describe('GraphQL API endpoint', () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
})
- it('should return 400 if request body is not valid JSON', async () => {
+ it('should return error if request body is not valid JSON', async () => {
const request = new Request('http://localhost/api/graphql', {
method: 'POST',
body: 'not json',
})
const response = await POST(request)
- expect(response.status).toBe(400)
- expect(await response.text()).toBe('Invalid request: Request body must be valid JSON')
+ const json = await response.json()
+ expect(json.errors[0].message).toBe('Invalid request: Request body must be valid JSON')
})
- it('should return 400 if request body is missing required fields', async () => {
+ it('should return error if request body is missing required fields', async () => {
const request = new Request('http://localhost/api/graphql', {
method: 'POST',
body: JSON.stringify({ variables: {} }),
})
const response = await POST(request)
- expect(response.status).toBe(400)
- expect(await response.text()).toContain('Request body must be a valid GraphQL request object')
+ const json = await response.json()
+ expect(json.errors[0].message).toContain(
+ 'Invalid request: Request body must be valid GraphQL request object'
+ )
})
- it('should return 400 if query is not a string', async () => {
+ it('should return error if query is not a string', async () => {
const request = new Request('http://localhost/api/graphql', {
method: 'POST',
body: JSON.stringify({ query: 123 }),
})
const response = await POST(request)
- expect(response.status).toBe(400)
+ const json = await response.json()
+ expect(json.errors[0].message).toContain(
+ 'Invalid request: Request body must be valid GraphQL request object'
+ )
})
- it('should return 500 for internal server errors', async () => {
+ it('should return error for internal server errors', async () => {
const request = new Request('http://localhost/api/graphql', {
method: 'POST',
body: JSON.stringify({ query: 'query { hello }' }),
@@ -50,7 +55,7 @@ describe('GraphQL API endpoint', () => {
})
const response = await POST(request)
- expect(response.status).toBe(500)
- expect(await response.text()).toBe('Internal Server Error')
+ const json = await response.json()
+ expect(json.errors[0].message).toBe('Internal Server Error')
})
})
diff --git a/apps/docs/app/api/graphql/route.ts b/apps/docs/app/api/graphql/route.ts
index 7efda7c254a..2655de05625 100644
--- a/apps/docs/app/api/graphql/route.ts
+++ b/apps/docs/app/api/graphql/route.ts
@@ -2,7 +2,7 @@ import { type DocumentNode, graphql, GraphQLError, parse, specifiedRules, valida
import { createComplexityLimitRule } from 'graphql-validation-complexity'
import { NextResponse } from 'next/server'
import { z } from 'zod'
-import { ApiError, InvalidRequestError } from '~/app/api/utils'
+import { ApiError, convertZodToInvalidRequestError, InvalidRequestError } from '~/app/api/utils'
import { rootGraphQLResolver } from '~/resources/rootResolver'
import { rootGraphQLSchema } from '~/resources/rootSchema'
import { createQueryDepthLimiter } from './validators'
@@ -16,14 +16,14 @@ const graphQLRequestSchema = z.object({
})
async function handleGraphQLRequest(request: Request): Promise<NextResponse> {
- const body = await request.json().catch(() => {
- throw new InvalidRequestError('Request body must be valid JSON')
+ const body = await request.json().catch((error) => {
+ throw new InvalidRequestError('Request body must be valid JSON', error)
})
const parsedBody = graphQLRequestSchema.safeParse(body)
if (!parsedBody.success) {
- const errorMessage = parsedBody.error?.message
- throw new InvalidRequestError(
- `Request body must be a valid GraphQL request object${errorMessage ? `: ${errorMessage}` : ''}`
+ throw convertZodToInvalidRequestError(
+ parsedBody.error,
+ 'Request body must be valid GraphQL request object'
)
}
@@ -47,10 +47,7 @@ async function handleGraphQLRequest(request: Request): Promise<NextResponse> {
variableValues: variables,
operationName,
})
- // return NextResponse.json(result)
-
- // For now, just return a 404 response
- return new NextResponse('Not Found', { status: 404 })
+ return NextResponse.json(result)
}
function validateGraphQLRequest(query: string): ReadonlyArray<GraphQLError> {
@@ -85,11 +82,13 @@ export async function POST(request: Request): Promise<NextResponse> {
console.error(error)
if (error instanceof ApiError) {
- return new NextResponse(error.isPrivate() ? 'Internal Server Error' : error.message, {
- status: error.statusCode(),
+ return NextResponse.json({
+ errors: [{ message: error.isPrivate() ? 'Internal Server Error' : error.message }],
})
} else {
- return new NextResponse('Internal Server Error', { status: 500 })
+ return NextResponse.json({
+ errors: [{ message: 'Internal Server Error' }],
+ })
}
}
}
diff --git a/apps/docs/app/api/utils.ts b/apps/docs/app/api/utils.ts
index 5b3f93ea15b..12e23bb605e 100644
--- a/apps/docs/app/api/utils.ts
+++ b/apps/docs/app/api/utils.ts
@@ -1,4 +1,4 @@
-import { z } from 'zod'
+import { z, type ZodError } from 'zod'
export class ApiError extends Error {
constructor(message: string) {
@@ -15,7 +15,7 @@ export class ApiError extends Error {
}
export class InvalidRequestError extends ApiError {
- constructor(message: string) {
+ constructor(message: string, source?: unknown) {
super(`Invalid request: ${message}`)
}
@@ -27,3 +27,14 @@ export class InvalidRequestError extends ApiError {
return 400
}
}
+
+export function convertZodToInvalidRequestError(
+ error: ZodError,
+ prelude?: string
+): InvalidRequestError {
+ const issue = error.issues[0]
+ const pathStr = issue.path.join('.')
+ const message = `${prelude ? `${prelude}: ` : ''}${issue.message} at key "${pathStr}"`
+
+ return new InvalidRequestError(message, error)
+}