70 lines
2.4 KiB
JavaScript
70 lines
2.4 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 url = req.url.split("?")[0];
|
|
|
|
// API: список заявок
|
|
if (req.method === "GET" && url === "/api/items") {
|
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
return res.end(JSON.stringify(readItems()));
|
|
}
|
|
|
|
// API: регистрация участника
|
|
if (req.method === "POST" && url === "/api/register") {
|
|
const item = await body(req);
|
|
if (!item.name || !item.phone || !item.email || !item.department) {
|
|
res.writeHead(400, { "Content-Type": "application/json" });
|
|
return res.end(JSON.stringify({ ok: false }));
|
|
}
|
|
const items = readItems();
|
|
items.push({
|
|
id: Date.now(),
|
|
name: String(item.name),
|
|
phone: String(item.phone),
|
|
email: String(item.email),
|
|
department: String(item.department),
|
|
tshirt: String(item.tshirt || "M"),
|
|
comment: String(item.comment || ""),
|
|
createdAt: new Date().toISOString()
|
|
});
|
|
writeItems(items);
|
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
return res.end(JSON.stringify({ ok: true }));
|
|
}
|
|
|
|
// Статика
|
|
let file = url === "/" ? "/index.html" : url;
|
|
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 === ".json" ? "application/json"
|
|
: ext === ".png" ? "image/png"
|
|
: 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("Сервер на порту " + PORT));
|