sozday-pomoschnika-pri-prove/server.js

61 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 load() {
try { return JSON.parse(fs.readFileSync(DATA, "utf8")); } catch (_) { return { items: [], log: [] }; }
}
function save(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({}); } });
});
}
const MIMES = { ".html": "text/html", ".css": "text/css", ".js": "application/javascript", ".json": "application/json", ".png": "image/png", ".svg": "image/svg+xml", ".ico": "image/x-icon", ".woff2": "font/woff2" };
http.createServer(async (req, res) => {
const url = req.url.split("?")[0];
if (req.method === "GET" && url === "/api/items") {
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify(load().items));
}
if (req.method === "POST" && url === "/api/items") {
const d = load();
const it = { id: Date.now(), ...await body(req) };
d.items.push(it);
d.log.push({ when: new Date().toISOString(), what: "добавлено: " + (it.title || ""), who: "юзер" });
save(d);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true, id: it.id }));
}
if (req.method === "DELETE" && url.startsWith("/api/items/")) {
const id = Number(url.split("/").pop());
const d = load();
const it = d.items.find((x) => x.id === id);
if (!it) { res.writeHead(404); return res.end("Not found"); }
d.items = d.items.filter((x) => x.id !== id);
d.log.push({ when: new Date().toISOString(), what: "удалено: " + (it.title || it.id), who: "юзер" });
save(d);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
let full = path.join(__dirname, url === "/" ? "/index.html" : url);
if (full.startsWith(__dirname) && fs.existsSync(full) && fs.statSync(full).isFile()) {
const ext = path.extname(full).toLowerCase();
res.writeHead(200, { "Content-Type": (MIMES[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));