otkryt-dannyy-proekt-i-dorab/server.js

83 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 readData() {
try { return JSON.parse(fs.readFileSync(DATA, "utf8")); } catch (_) { return { orders: [] }; }
}
function writeData(data) {
fs.writeFileSync(DATA, JSON.stringify(data, 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) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
if (req.method === "OPTIONS") {
res.writeHead(200);
return res.end();
}
if (req.method === "GET" && req.url === "/api/data") {
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify(readData()));
}
if (req.method === "POST" && req.url === "/api/data") {
const data = readData();
const item = await body(req);
item.id = parseInt(item.id) || Date.now();
data.orders.push(item);
writeData(data);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true, item }));
}
if (req.method === "PUT" && req.url.startsWith("/api/data/")) {
const id = parseInt(req.url.split("/").pop());
const data = readData();
const idx = data.orders.findIndex(i => i.id === id);
if (idx !== -1) {
const update = await body(req);
data.orders[idx] = { ...data.orders[idx], ...update };
writeData(data);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
res.writeHead(404, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ error: "Not found" }));
}
if (req.method === "DELETE" && req.url.startsWith("/api/data/")) {
const id = parseInt(req.url.split("/").pop());
const data = readData();
data.orders = data.orders.filter(i => i.id !== id);
writeData(data);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
let file = req.url === "/" ? "/index.html" : req.url.split("?")[0];
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" : ext === ".svg" ? "image/svg+xml" : "text/html";
res.writeHead(200, { "Content-Type": type + "; charset=utf-8" });
return res.end(fs.readFileSync(full));
}
res.writeHead(404, { "Content-Type": "text/html" });
res.end("Not found");
}).listen(PORT, () => console.log("Dashboard running on port " + PORT));