47 lines
1.4 KiB
TypeScript
47 lines
1.4 KiB
TypeScript
import { HttpError } from "./error.ts"
|
|
|
|
type HttpMethod = "GET" | "POST" | "DELETE" | "PUT" | "OPTIONS" | "PATCH"
|
|
|
|
const ALLOWED_ORIGINS = ["http://localhost:5173"]
|
|
|
|
function httpHandler<Route extends string>(
|
|
handler: (request: Bun.BunRequest<Route>) => Promise<Response>,
|
|
): (request: Bun.BunRequest<Route>) => Promise<Response> {
|
|
return async (request) => {
|
|
let response: Response
|
|
try {
|
|
response = await handler(request)
|
|
} catch (error) {
|
|
if (error instanceof HttpError) {
|
|
if (error.message || error.code) {
|
|
response = Response.json({ code: error.code, message: error.message }, { status: error.status })
|
|
} else {
|
|
response = new Response(undefined, { status: error.status })
|
|
}
|
|
} else {
|
|
console.error(error)
|
|
response = new Response(undefined, { status: 500 })
|
|
}
|
|
}
|
|
for (const origin of ALLOWED_ORIGINS) {
|
|
response.headers.set("Access-Control-Allow-Origin", origin)
|
|
}
|
|
response.headers.set("Access-Control-Allow-Credentials", "true")
|
|
return response
|
|
}
|
|
}
|
|
|
|
function preflightHandler<Route extends string>({ allowedMethods }: { allowedMethods: HttpMethod[] }) {
|
|
return async (request: Bun.BunRequest<Route>) =>
|
|
new Response(undefined, {
|
|
status: 200,
|
|
headers: {
|
|
"Access-Control-Allow-Origin": ALLOWED_ORIGINS.join(", "),
|
|
"Access-Control-Allow-Methods": allowedMethods.join(", "),
|
|
"Access-Control-Allow-Credentials": "true",
|
|
},
|
|
})
|
|
}
|
|
|
|
export { httpHandler, preflightHandler }
|