sozday-sayt-dlya-prodazhi-od/server.js

66 lines
2.5 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 readOrders() {
try { return JSON.parse(fs.readFileSync(DATA, "utf8")); } catch (_) { return []; }
}
function writeOrders(orders) {
fs.writeFileSync(DATA, JSON.stringify(orders, null, 2));
}
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({}); } });
});
}
http.createServer(async (req, res) => {
const url = req.url.split("?")[0];
if (req.method === "GET" && url === "/api/orders") {
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify(readOrders()));
}
if (req.method === "POST" && url === "/api/order") {
const b = await readBody(req);
if (!b.name || !b.phone) {
res.writeHead(400, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: false, error: "Укажите имя и телефон" }));
}
const orders = readOrders();
const order = {
id: Date.now(),
name: String(b.name).slice(0, 100),
phone: String(b.phone).slice(0, 40),
address: String(b.address || "").slice(0, 300),
comment: String(b.comment || "").slice(0, 500),
status: "новый",
items: Array.isArray(b.items) ? b.items.slice(0, 50).map((it) => ({ id: it.id, qty: it.qty })) : [],
sum: 0,
createdAt: new Date().toISOString()
};
orders.push(order);
writeOrders(orders);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
// Статика под любым под-путём (pages/proxy работают)
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" :
ext === ".json" ? "application/json" : "text/html";
res.writeHead(200, { "Content-Type": type + "; charset=utf-8" });
return res.end(fs.readFileSync(full));
}
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not found");
}).listen(PORT, () => console.log("Сервер MODA на порту " + PORT));