Files
markone/packages/server/src/http-handler.ts

47 lines
1.4 KiB
TypeScript
Raw Normal View History

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