// run with `bun run index.js` import { Database } from "bun:sqlite"; import { serve } from "bun"; export class App { constructor(db) { this.db = db; } async handleShorten(req) { const { targetUrl, sid: customSid } = await req.json(); const sid = customSid || Buffer.from(crypto.getRandomValues(new Uint8Array(6))) .toString("base64url") .substring(0, 8); this.db.run(`INSERT INTO urls(sid, originalURL) VALUES(?, ?)`, [ sid, targetUrl, ]); return Response.json({ status: "success", shortUrl: `http://localhost:9172/${sid}`, }); } async handleHealthz() { return Response.json({ msg: "OK" }); } } const db = new Database(":memory:"); const app = new App(db); db.run(` CREATE TABLE IF NOT EXISTS urls ( id INTEGER PRIMARY KEY AUTOINCREMENT, sid TEXT UNIQUE, originalURL TEXT NOT NULL ) `); const server = serve({ port: 9173, routes: { "/api/healthz": app.handleHealthz, // WORKS "/api/shorten": app.handleShorten, // DOES NOT WORK // "/api/shorten": (req) => app.handleShorten(req) // WORKS }, }); console.log(`server running at ${server.url}`);