Skip to content

Instantly share code, notes, and snippets.

@ThatXliner
Created November 24, 2024 06:32
Show Gist options
  • Save ThatXliner/90a0e82699a885974404bf31929e1a02 to your computer and use it in GitHub Desktop.
Save ThatXliner/90a0e82699a885974404bf31929e1a02 to your computer and use it in GitHub Desktop.
bun run main.ts
import { Database } from "bun:sqlite";
const db = new Database("logs.sqlite", { strict: true });
await db.run(
`CREATE TABLE IF NOT EXISTS logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
data TEXT NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)`,
);
const PORT = Bun.argv[2] ?? 3000;
const query = db.query("INSERT INTO logs (data) VALUES ($text)");
console.log(`Listening on http://0.0.0.0:${PORT}`);
Bun.serve({
// port: 3000, // defaults to $BUN_PORT, $PORT, $NODE_PORT otherwise 3000
// hostname: "mydomain.com", // defaults to "0.0.0.0"
async fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/")
return new Response(
`
<!DOCTYPE html>
<html>
<body>
<p>Visit <a href="/logs">/logs</a> to view logs</p>
</body>
</html>
`,
{
headers: {
"Content-Type": "text/html",
},
},
);
if (url.pathname === "/blog") {
const logs = (await db.query("SELECT * FROM logs").all()) as {
id: number;
data: string;
timestamp: Date;
}[];
const csv = logs
.map((log) => `${log.id},${log.data},${log.timestamp}`)
.join("\n");
console.log(csv);
return new Response(csv, {
headers: {
"Content-Type": "text/csv",
},
});
}
if (url.pathname === "/add") {
const body = await req.json();
await query.run({ text: body.text });
return new Response("Added!", {
headers: {
"Content-Type": "text/plain",
},
});
}
return new Response("404!");
},
error(error) {
return new Response(`<pre>${error}\n${error.stack}</pre>`, {
headers: {
"Content-Type": "text/html",
},
});
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment