import { parse } from "./duration"; import { perform } from "./email"; import type { EmailJob } from "./job"; 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 = await req.json(); const interval = parse(prevalidatedJob.readRetry.interval); if (interval._tag === "Left") { return new Response(interval.left, { status: 400 }); } prevalidatedJob.readRetry.interval = interval; const job: EmailJob = { ...prevalidatedJob, readRetry: { ...prevalidatedJob.readRetry, interval }, }; 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; };