uptime/src/api.ts

53 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-12-15 02:53:26 -05:00
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 job: EmailJob = await req.json();
const jobInsensitive = structuredClone(job);
jobInsensitive.from.username = "****REDACTED****";
jobInsensitive.from.password = "****REDACTED****";
jobInsensitive.to.username = "****REDACTED****";
jobInsensitive.to.password = "****REDACTED****";
2024-12-15 03:00:32 -05:00
const uuid = crypto.randomUUID();
2024-12-15 02:53:26 -05:00
ConsoleLogger.log(
2024-12-15 03:00:32 -05:00
`[${uuid}] Received email job: ${JSON.stringify(jobInsensitive)}`,
2024-12-15 02:53:26 -05:00
)();
const performEmailTest = perform(job)();
2024-12-15 03:00:32 -05:00
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`)();
2024-12-15 02:53:26 -05:00
return Response.json({ success: true });
})
2024-12-15 03:00:32 -05:00
.catch((e) => {
ConsoleLogger.log(`[${uuid}] internal failure due to ${e}`)();
return new Response(e.message, {
status: 500,
2024-12-15 02:53:26 -05:00
});
});
}
return new Response("404!", { status: 404 });
},
});
ConsoleLogger.log(`Listening on port ${port}`)();
return server;
};