41 lines
1.1 KiB
TypeScript
41 lines
1.1 KiB
TypeScript
export type JsonBody = Record<string, unknown> | unknown[]
|
|
|
|
const corsHeaders = {
|
|
'Access-Control-Allow-Origin': '*',
|
|
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
|
'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS'
|
|
}
|
|
|
|
export const json = (body: JsonBody, init: ResponseInit = {}) =>
|
|
Response.json(body, {
|
|
...init,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
...corsHeaders,
|
|
...(init.headers || {})
|
|
}
|
|
})
|
|
|
|
export const ok = (data: unknown = null) => json({ success: true, data })
|
|
|
|
export const fail = (message: string, status = 400, code = 'BAD_REQUEST') =>
|
|
json({ success: false, error: { code, message } }, { status })
|
|
|
|
export const methodNotAllowed = (allowedMethods: string[]) =>
|
|
json(
|
|
{ success: false, error: { code: 'METHOD_NOT_ALLOWED', message: '请求方式不支持' } },
|
|
{
|
|
status: 405,
|
|
headers: {
|
|
...corsHeaders,
|
|
Allow: allowedMethods.join(', ')
|
|
}
|
|
}
|
|
)
|
|
|
|
export const handleOptions = () =>
|
|
new Response(null, {
|
|
status: 204,
|
|
headers: corsHeaders
|
|
})
|