sozday-mne-formu-registratsi-2/server.js

58 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({}); } });
});
}
const FIELDS = ["fio", "dept", "position", "phone", "email", "guests", "comment"];
http.createServer(async (req, res) => {
const url = req.url.split("?")[0];
if (req.method === "GET" && url === "/api/registrations") {
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify(readItems()));
}
if (req.method === "POST" && url === "/api/register") {
const item = await body(req);
const rec = {};
FIELDS.forEach((f) => { rec[f] = String(item[f] || "").trim(); });
rec.guests = String(parseInt(item.guests, 10) || 0);
if (!rec.fio || !rec.phone || !rec.email) {
res.writeHead(400, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: false, error: "Заполните ФИО, телефон и email" }));
}
const items = readItems();
items.push({ id: Date.now(), date: new Date().toISOString(), ...rec });
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 types = { ".css": "text/css", ".js": "application/javascript", ".html": "text/html", ".json": "application/json", ".svg": "image/svg+xml", ".png": "image/png", ".woff2": "font/woff2" };
res.writeHead(200, { "Content-Type": (types[ext] || "application/octet-stream") + "; charset=utf-8" });
return res.end(fs.readFileSync(full));
}
res.writeHead(404); res.end("Not found");
}).listen(PORT, () => console.log("Сервер регистрации на порту " + PORT));