uptime/src/api.ts

64 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-12-15 05:07:48 -05:00
import { parse } from "./duration";
2024-12-15 02:53:26 -05:00
import { perform } from "./email";
2024-12-15 05:07:48 -05:00
import type { EmailJob } from "./job";
2024-12-15 02:53:26 -05:00
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") {
2024-12-15 05:07:48 -05:00
const prevalidatedJob = await req.json();
const interval = parse(prevalidatedJob.readRetry.interval);
if (interval._tag === "Left") {
return new Response(interval.left, { status: 400 });
2024-12-15 04:57:28 -05:00
}
2024-12-15 05:07:48 -05:00
prevalidatedJob.readRetry.interval = interval;
const job: EmailJob = {
...prevalidatedJob,
readRetry: { ...prevalidatedJob.readRetry, interval },
};
2024-12-15 02:53:26 -05:00
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;
};