sozday-mne-formu-dlya-meropr/server.js

68 lines
2.6 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 readData() {
try { return JSON.parse(fs.readFileSync(DATA, "utf8")); } 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];
if (req.method === "GET" && url === "/api/registrations") {
const d = readData();
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
return res.end(JSON.stringify(d.registrations));
}
if (req.method === "POST" && url === "/api/registrations") {
const r = await body(req);
if (!r.name || !r.phone) {
res.writeHead(400, { "Content-Type": "application/json; charset=utf-8" });
return res.end(JSON.stringify({ ok: false, error: "name and phone are required" }));
}
const d = readData();
const rec = {
id: Date.now(),
name: String(r.name).trim(),
dept: String(r.dept || "").trim(),
phone: String(r.phone).trim(),
email: String(r.email || "").trim(),
size: String(r.size || "").trim(),
allergies: String(r.allergies || "").trim(),
comment: String(r.comment || "").trim(),
createdAt: new Date().toISOString()
};
d.registrations.push(rec);
writeData(d);
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
return res.end(JSON.stringify({ ok: true, id: rec.id }));
}
const safe = decodeURIComponent(url) || "/";
let file = safe === "/" ? "/index.html" : safe;
const full = path.join(__dirname, file);
if (full.startsWith(__dirname) && fs.existsSync(full) && fs.statSync(full).isFile()) {
const ext = path.extname(full).toLowerCase();
const types = { ".css": "text/css", ".js": "application/javascript", ".html": "text/html", ".png": "image/png", ".svg": "image/svg+xml", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".ico": "image/x-icon" };
res.writeHead(200, { "Content-Type": (types[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));