62 lines
2.2 KiB
JavaScript
62 lines
2.2 KiB
JavaScript
// Реестр участников тимбилдинга: GET/POST /api/participants + статика проекта.
|
|
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 readItems() {
|
|
try { return JSON.parse(fs.readFileSync(DATA, "utf8")); } catch (_) { return []; }
|
|
}
|
|
function writeItems(items) {
|
|
fs.writeFileSync(DATA, JSON.stringify(items, 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({}); } });
|
|
});
|
|
}
|
|
|
|
const MIME = {
|
|
".html": "text/html", ".css": "text/css", ".js": "application/javascript",
|
|
".json": "application/json", ".svg": "image/svg+xml", ".png": "image/png"
|
|
};
|
|
|
|
http.createServer(async (req, res) => {
|
|
const url = req.url.split("?")[0];
|
|
|
|
if (req.method === "GET" && url === "/api/participants") {
|
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
return res.end(JSON.stringify(readItems()));
|
|
}
|
|
if (req.method === "POST" && url === "/api/participants") {
|
|
const it = await body(req);
|
|
const items = readItems();
|
|
const rec = {
|
|
id: Date.now(),
|
|
name: String(it.name || "").trim(),
|
|
lastname: String(it.lastname || "").trim(),
|
|
phone: String(it.phone || "").trim(),
|
|
status: "waiting",
|
|
date: it.date || new Date().toISOString().slice(0, 10)
|
|
};
|
|
items.push(rec);
|
|
writeItems(items);
|
|
res.writeHead(201, { "Content-Type": "application/json" });
|
|
return res.end(JSON.stringify({ ok: true, record: rec }));
|
|
}
|
|
|
|
let file = url === "/" ? "/index.html" : url;
|
|
const full = path.join(__dirname, decodeURIComponent(file));
|
|
if (full.startsWith(__dirname) && fs.existsSync(full) && fs.statSync(full).isFile()) {
|
|
const ext = path.extname(full);
|
|
res.writeHead(200, { "Content-Type": (MIME[ext] || "application/octet-stream") + "; charset=utf-8" });
|
|
return res.end(fs.readFileSync(full));
|
|
}
|
|
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
|
|
res.end("Not found");
|
|
}).listen(PORT, () => console.log("Регистрация тимбилдинга на порту " + PORT));
|