66 lines
2.3 KiB
JavaScript
66 lines
2.3 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 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({}); } });
|
|
});
|
|
}
|
|
|
|
http.createServer(async (req, res) => {
|
|
const urlPath = req.url.split("?")[0];
|
|
|
|
if (req.method === "GET" && urlPath === "/api/registrations") {
|
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
return res.end(JSON.stringify(readItems()));
|
|
}
|
|
|
|
if (req.method === "POST" && urlPath === "/api/registrations") {
|
|
const item = await body(req);
|
|
const items = readItems();
|
|
const newItem = {
|
|
id: Date.now(),
|
|
firstName: item.firstName || "",
|
|
lastName: item.lastName || "",
|
|
phone: item.phone || "",
|
|
telegram: item.telegram || "",
|
|
registeredAt: new Date().toISOString()
|
|
};
|
|
items.push(newItem);
|
|
writeItems(items);
|
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
return res.end(JSON.stringify({ ok: true, data: newItem }));
|
|
}
|
|
|
|
if (req.method === "GET" && urlPath === "/api/stats") {
|
|
const items = readItems();
|
|
const today = new Date().toDateString();
|
|
const todayCount = items.filter(p => new Date(p.registeredAt).toDateString() === today).length;
|
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
return res.end(JSON.stringify({ total: items.length, today: todayCount }));
|
|
}
|
|
|
|
let file = req.url === "/" ? "/index.html" : urlPath;
|
|
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" : "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("Сервер запущен на порту " + PORT));
|