mirror of
https://github.com/supabase/supabase.git
synced 2026-09-07 02:20:52 +08:00
## Context As per PR title - also adjusts the imports for files consuming `apiWrapper` to remove the default export for `apiWrapper` Have tested locally by throwing an error in one of the API routes - verified that the event shows up on Sentry <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * API errors are now captured in Sentry before returning server error responses, improving production visibility while keeping endpoint behavior the same. * **Tests** * Added coverage to confirm rejected handler executions are reported to Sentry and return the expected HTTP 500 JSON payload. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
60 lines
1.6 KiB
TypeScript
60 lines
1.6 KiB
TypeScript
import * as Sentry from '@sentry/nextjs'
|
|
import type { JwtPayload } from '@supabase/supabase-js'
|
|
import type { NextApiRequest, NextApiResponse } from 'next'
|
|
|
|
import { IS_PLATFORM } from '../constants'
|
|
import { apiAuthenticate } from './apiAuthenticate'
|
|
import { ResponseError, ResponseFailure } from '@/types'
|
|
|
|
export function isResponseOk<T>(response: T | ResponseFailure | undefined): response is T {
|
|
if (response === undefined || response === null) {
|
|
return false
|
|
}
|
|
|
|
if (response instanceof ResponseError) {
|
|
return false
|
|
}
|
|
|
|
if (typeof response === 'object' && 'error' in response && Boolean(response.error)) {
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
// Purpose of this apiWrapper is to function like a global catchall for ANY errors
|
|
// It's a safety net as the API service should never drop, nor fail
|
|
|
|
export async function apiWrapper(
|
|
req: NextApiRequest,
|
|
res: NextApiResponse,
|
|
handler: (
|
|
req: NextApiRequest,
|
|
res: NextApiResponse,
|
|
claims?: JwtPayload
|
|
) => Promise<NextApiResponse | Response | void>,
|
|
options?: { withAuth: boolean }
|
|
): Promise<NextApiResponse | Response | void> {
|
|
try {
|
|
const { withAuth } = options || {}
|
|
let claims: JwtPayload | undefined
|
|
|
|
if (IS_PLATFORM && withAuth) {
|
|
const response = await apiAuthenticate(req, res)
|
|
if (!isResponseOk(response)) {
|
|
return res.status(401).json({
|
|
error: {
|
|
message: `Unauthorized: ${response.error.message}`,
|
|
},
|
|
})
|
|
}
|
|
claims = response
|
|
}
|
|
|
|
return await handler(req, res, claims)
|
|
} catch (error) {
|
|
Sentry.captureException(error)
|
|
return res.status(500).json({ error })
|
|
}
|
|
}
|