import * as oak from "jsr:@oak/oak"; const port = Number(Deno.env.get("PORT") ?? 8000); const router = new oak.Router(); router.post("/api/log", async (ctx) => { const data = await ctx.request.body.json(); console.log(`POST /api/log ${JSON.stringify(data)}`); const enc = new TextEncoder(); const postLog = await Deno.open("./data/log.txt", { append: true, create: true, }); postLog.write( enc.encode(`${new Date().toISOString()}\t${JSON.stringify(data)}\n`), ); ctx.response.body = { ok: true }; ctx.respond = true; }); router.get("/api/log", async (ctx) => { const postLog = await Deno.readTextFile("./data/log.txt"); const entries = postLog .split("\n") .filter((l) => l) .map((entry) => entry.split("\t")) .map(([timestamp, data]) => ({ timestamp: new Date(timestamp), data: JSON.parse(data), })); ctx.response.body = entries; ctx.respond = true; }); console.log(`listening at http://localhost:${port}/`); new oak.Application() .use(router.routes()) .use(router.allowedMethods()) .use(async (ctx) => { const { request: { url: { pathname } } } = ctx; await oak.send(ctx, pathname, { root: "./public", index: "index.html", }); }) .listen({ port });