sdelay-sayt-kibergigieny-dly/server.js

68 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 { incidents: [] }; }
}
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({}); } });
});
}
function sanitizeContact(c) {
// Храним только короткий контакт: имя или e-mail, без свободного текста
if (!c) return "";
return String(c).replace(/[<>]/g, "").slice(0, 80);
}
http.createServer(async (req, res) => {
const url = req.url.split("?")[0];
// API: получить обезличенную статистику
if (req.method === "GET" && url === "/api/stats") {
const d = readItems();
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({
incidents: (d.incidents || []).length
}));
}
// API: добавить анонимное сообщение об инциденте
if (req.method === "POST" && url === "/api/incidents") {
const b = await body(req);
const d = readItems();
if (!d.incidents) d.incidents = [];
d.incidents.push({
id: Date.now(),
type: String(b.type || "").slice(0, 40),
description: String(b.description || "").slice(0, 1000),
contact: sanitizeContact(b.contact),
createdAt: new Date().toISOString()
});
writeItems(d);
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" : "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));