kalendar/server.js
2026-07-31 10:09:36 +00:00

82 lines
3.0 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 { notes: [] }; }
}
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({}); } });
});
}
http.createServer(async (req, res) => {
const url = req.url.split("?")[0];
// Список всех заметок (опционально фильтр по дате)
if (req.method === "GET" && url === "/api/notes") {
const q = new URL(req.url, "http://x").searchParams;
const date = q.get("date");
const db = load();
const list = date ? db.notes.filter((n) => n.date === date) : db.notes;
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify(list));
}
// Добавить заметку
if (req.method === "POST" && url === "/api/notes") {
const note = await body(req);
if (!note.date || !note.text) {
res.writeHead(400, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: false, error: "date и text обязательны" }));
}
const db = load();
const item = { id: Date.now(), date: note.date, text: String(note.text).slice(0, 300), done: !!note.done };
db.notes.push(item);
save(db);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify(item));
}
// Переключить «сделано»
if (req.method === "PATCH" && url === "/api/notes") {
const patch = await body(req);
const db = load();
const note = db.notes.find((n) => n.id === patch.id);
if (note) note.done = !!patch.done;
save(db);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: !!note }));
}
// Удалить заметку
if (req.method === "DELETE" && url.startsWith("/api/notes/")) {
const id = Number(url.split("/").pop());
const db = load();
db.notes = db.notes.filter((n) => n.id !== id);
save(db);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
// Статика: index.html / style.css / script.js
let file = req.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));