import { transformDurations } from "./duration"; import { perform } from "./email"; import { ConsoleLogger } from "./logger"; export const main = (port: number) => { const server = Bun.serve({ port, async fetch(req) { ConsoleLogger.log(`Received request: ${req.url}`)(); const url = new URL(req.url); if (req.method === "POST" && url.pathname === "/api/email") { const prevalidatedJob = transformDurations(await req.json()); if (prevalidatedJob._tag === "Left") { return new Response(prevalidatedJob.left, { status: 400 }); } const job = prevalidatedJob.right; const jobInsensitive = structuredClone(job); jobInsensitive.from.username = "****REDACTED****"; jobInsensitive.from.password = "****REDACTED****"; jobInsensitive.to.username = "****REDACTED****"; jobInsensitive.to.password = "****REDACTED****"; const uuid = crypto.randomUUID(); ConsoleLogger.log( `[${uuid}] Received email job: ${JSON.stringify(jobInsensitive)}`, )(); const performEmailTest = perform(job)(); return performEmailTest .then((result) => { if (result._tag === "Left") { const error = result.left; ConsoleLogger.log( `[${uuid}] job failure due to ${error.message}`, )(); return new Response(error.message, { status: 400, }); } ConsoleLogger.log(`[${uuid}] success`)(); return Response.json({ success: true }); }) .catch((e) => { ConsoleLogger.log(`[${uuid}] internal failure due to ${e}`)(); return new Response(e.message, { status: 500, }); }); } return new Response("404!", { status: 404 }); }, }); ConsoleLogger.log(`Listening on port ${port}`)(); return server; };