Files
supabase/apps/studio/lib/api/apiWrapper.ts
Joshen Lim dbb413beeb Chore/deprecate lib common fetch 03 (#36529)
* Deprecate use of getWithTimeout, refactor BuildingState and RestoringState to use RQ

* Refactor profile-create-mutation to use data/fetchers, and edge-function-status-query to use fetch

* Shift post from lib/common/fetch, refactor bucket-object-download-mutation

* Address feedback

* Minor fix

* Refactor post calls from lib/common/fetch in auth pages to data/fetchers

* Add missing POST users endpoint + small fix when deleting user via context menu

* Remove all use of any imports from lib/common/fetch

* Clean up remaining usage of lib/common/fetch

* Fix fetchHeadWithTimeout

* simplify handleFetchError

* allow handleFetchError to accept unknown

* non-breaking change

* small fixes

* fix query path

---------

Co-authored-by: Alaister Young <a@alaisteryoung.com>
2025-07-21 16:59:17 +08:00

54 lines
1.4 KiB
TypeScript

import type { NextApiHandler, NextApiRequest, NextApiResponse } from 'next'
import { ResponseError, ResponseFailure } from 'types'
import { IS_PLATFORM } from '../constants'
import { apiAuthenticate } from './apiAuthenticate'
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 default async function apiWrapper(
req: NextApiRequest,
res: NextApiResponse,
handler: NextApiHandler,
options?: { withAuth: boolean }
) {
try {
const { withAuth } = options || {}
if (IS_PLATFORM && withAuth) {
const response = await apiAuthenticate(req, res)
if (!isResponseOk(response)) {
return res.status(401).json({
error: {
message: `Unauthorized: ${response.error.message}`,
},
})
} else {
// Attach user information to request parameters
;(req as any).user = response
}
}
return handler(req, res)
} catch (error) {
return res.status(500).json({ error })
}
}