import { HttpError } from "./error.ts" type HttpMethod = "GET" | "POST" | "DELETE" | "PUT" | "OPTIONS" | "PATCH" const ALLOWED_ORIGINS = ["http://localhost:5173"] function httpHandler( handler: (request: Bun.BunRequest) => Promise, ): (request: Bun.BunRequest) => Promise { 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({ allowedMethods }: { allowedMethods: HttpMethod[] }) { return async (request: Bun.BunRequest) => 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 }