52 lines
2.0 KiB
JavaScript
52 lines
2.0 KiB
JavaScript
const http = require("http");
|
|
const fs = require("fs");
|
|
const path = require("path");
|
|
|
|
const PORT = process.env.PORT || 3000;
|
|
const DATA = path.join(__dirname, "data.json");
|
|
|
|
function readAll() {
|
|
try { return JSON.parse(fs.readFileSync(DATA, "utf8")); } catch (_) { return { rsvps: [] }; }
|
|
}
|
|
function writeAll(d) {
|
|
fs.writeFileSync(DATA, JSON.stringify(d, null, 2));
|
|
}
|
|
function body(req) {
|
|
return new Promise((resolve) => {
|
|
let s = "";
|
|
req.on("data", (c) => (s += c));
|
|
req.on("end", () => { try { resolve(JSON.parse(s || "{}")); } catch (_) { resolve({}); } });
|
|
});
|
|
}
|
|
|
|
http.createServer(async (req, res) => {
|
|
if (req.method === "POST" && req.url.split("?")[0] === "/api/rsvp") {
|
|
const item = await body(req);
|
|
const d = readAll();
|
|
d.rsvps.push({
|
|
id: Date.now(),
|
|
name: String(item.name || "").slice(0, 80),
|
|
guests: parseInt(item.guests, 10) || 1,
|
|
attendance: item.attendance === "no" ? "no" : "yes",
|
|
note: String(item.note || "").slice(0, 300),
|
|
createdAt: new Date().toISOString(),
|
|
});
|
|
writeAll(d);
|
|
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
|
|
return res.end(JSON.stringify({ ok: true }));
|
|
}
|
|
if (req.method === "GET" && req.url.split("?")[0] === "/api/rsvp") {
|
|
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
|
|
return res.end(JSON.stringify(readAll().rsvps));
|
|
}
|
|
let file = req.url === "/" ? "/index.html" : req.url.split("?")[0];
|
|
const full = path.join(__dirname, file);
|
|
if (full.startsWith(__dirname) && fs.existsSync(full) && fs.statSync(full).isFile()) {
|
|
const ext = path.extname(full);
|
|
const type = ext === ".css" ? "text/css" : ext === ".js" ? "application/javascript" : ext === ".svg" ? "image/svg+xml" : "text/html";
|
|
res.writeHead(200, { "Content-Type": type + "; charset=utf-8" });
|
|
return res.end(fs.readFileSync(full));
|
|
}
|
|
res.writeHead(404); res.end("Not found");
|
|
}).listen(PORT, () => console.log("Server on port " + PORT));
|