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,
"/api/shorten": app.handleShorten,
},
});
console.log(`server running at ${server.url}`);