ya-hochu-sozdat-odnostranich/server.js

137 lines
4.3 KiB
JavaScript

const http = require("http");
const fs = require("fs");
const path = require("path");
const PORT = process.env.PORT || 3000;
const DATA_FILE = path.join(__dirname, "data.json");
const ROOT = __dirname;
const BOARD_KEYS = new Set(["gdplan", "myplan", "notes"]);
const MIME = {
".css": "text/css", ".js": "application/javascript",
".html": "text/html", ".json": "application/json",
".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon",
".woff2": "font/woff2", ".woff": "font/woff", ".txt": "text/plain"
};
function readData() {
try { return JSON.parse(fs.readFileSync(DATA_FILE, "utf8")); }
catch (_) { return { gdplan: [], myplan: [], notes: [] }; }
}
function saveData(d) { fs.writeFileSync(DATA_FILE, JSON.stringify(d, null, 2)); }
function sendJson(res, code, obj) {
const body = JSON.stringify(obj);
res.writeHead(code, {
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Origin": "*",
"Cache-Control": "no-store"
});
res.end(body);
}
function readBody(req) {
return new Promise(resolve => {
let s = "";
req.on("data", c => (s += c));
req.on("end", () => { try { resolve(JSON.parse(s || "{}")); } catch (_) { resolve({}); } });
});
}
function sanitize(key, item) {
const base = { id: Number(item.id) || Date.now() };
if (key === "notes") {
base.text = String(item.text || "").slice(0, 2000);
return base;
}
base.text = String(item.text || "").slice(0, 500);
base.status = ["todo", "doing", "done"].includes(item.status) ? item.status : "todo";
base.due = String(item.due || "").slice(0, 10);
return base;
}
const server = http.createServer(async (req, res) => {
const url0 = req.url.split("?")[0];
// CORS preflight
if (req.method === "OPTIONS") {
res.writeHead(204, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type"
});
return res.end();
}
// ---- API ----
if (url0.startsWith("/api/board/")) {
const key = url0.split("/")[3];
if (!BOARD_KEYS.has(key)) return sendJson(res, 400, { ok: false, error: "unknown board" });
if (req.method === "GET") {
const d = readData();
return sendJson(res, 200, d[key] || []);
}
const body = await readBody(req);
if (req.method === "POST") {
const d = readData();
const arr = d[key] || [];
const newId = arr.length ? Math.max(...arr.map(x => x.id)) + 1 : 1;
const item = sanitize(key, { ...body, id: newId });
arr.push(item);
d[key] = arr;
saveData(d);
return sendJson(res, 200, { ok: true, item });
}
// PUT / DELETE требуют id
const m = url0.match(/^\/api\/board\/(\w+)\/(\d+)$/);
if (m) {
const id = Number(m[2]);
const d = readData();
const arr = d[key] || [];
if (req.method === "PUT") {
const idx = arr.findIndex(x => x.id === id);
if (idx < 0) return sendJson(res, 404, { ok: false, error: "not found" });
arr[idx] = { ...arr[idx], ...sanitize(key, { ...arr[idx], ...body }) };
saveData(d);
return sendJson(res, 200, { ok: true, item: arr[idx] });
}
if (req.method === "DELETE") {
const next = arr.filter(x => x.id !== id);
d[key] = next;
saveData(d);
return sendJson(res, 200, { ok: true });
}
}
return sendJson(res, 405, { ok: false, error: "method not allowed" });
}
if (url0 === "/api/news") {
// Заглушка: реальных источников нет — возвращаем пустой список.
return sendJson(res, 200, []);
}
// ---- Статика ----
let file = url0 === "/" ? "/index.html" : url0;
const full = path.join(ROOT, file);
if (full.startsWith(ROOT) && fs.existsSync(full)) {
const st = fs.statSync(full);
if (st.isFile()) {
const ext = path.extname(full).toLowerCase();
const type = MIME[ext] || "application/octet-stream";
res.writeHead(200, { "Content-Type": type + "; charset=utf-8" });
return res.end(fs.readFileSync(full));
}
}
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
res.end("Not found");
});
server.listen(PORT, () => console.log("Сервер запущен на порту " + PORT));