sozdat-proekt-priglasheniya/server.js

74 lines
2.7 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");
// data.json: { registrations: [...] } — плоский массив, юзер видит во вкладке «Данные»
function readData() {
try {
const d = JSON.parse(fs.readFileSync(DATA, "utf8"));
if (!d.registrations) d.registrations = [];
return d;
} catch (_) { return { registrations: [] }; }
}
function writeData(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) => {
const url = req.url.split("?")[0];
// API: список подтверждений (для проверки)
if (req.method === "GET" && url === "/api/confirmations") {
const d = readData();
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify(d.registrations));
}
// API: сохранить подтверждение
if (req.method === "POST" && url === "/api/confirmation") {
const it = await body(req);
const d = readData();
d.registrations.push({
id: Date.now(),
name: String(it.name || "").slice(0, 120),
role: String(it.role || "").slice(0, 120),
contact: String(it.contact || "").slice(0, 80),
notes: String(it.notes || "").slice(0, 500),
createdAt: new Date().toISOString()
});
writeData(d);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
// Статика: index.html / script.js / documents/… / design-system/…
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 types = {
".css": "text/css",
".js": "application/javascript",
".html": "text/html",
".svg": "image/svg+xml",
".png": "image/png",
".json": "application/json",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
};
const isText = [".css", ".js", ".html", ".svg", ".json"].includes(ext);
res.writeHead(200, { "Content-Type": (types[ext] || "application/octet-stream") + (isText ? "; charset=utf-8" : "") });
return res.end(fs.readFileSync(full));
}
res.writeHead(404); res.end("Not found");
}).listen(PORT, () => console.log("Сервер на порту " + PORT));