72 lines
1.9 KiB
JavaScript
72 lines
1.9 KiB
JavaScript
const http = require("http");
|
|
const fs = require("fs");
|
|
const path = require("path");
|
|
|
|
const PORT = process.env.LAYOUT_SERVER_PORT || 4001;
|
|
const LAYOUT_PATH = path.join(__dirname, "..", "config", "layout.json");
|
|
|
|
function sendJson(res, status, data) {
|
|
res.writeHead(status, {
|
|
"Content-Type": "application/json",
|
|
"Access-Control-Allow-Origin": "*",
|
|
});
|
|
res.end(JSON.stringify(data, null, 2));
|
|
}
|
|
|
|
function sendText(res, status, text) {
|
|
res.writeHead(status, {
|
|
"Content-Type": "text/plain",
|
|
"Access-Control-Allow-Origin": "*",
|
|
});
|
|
res.end(text);
|
|
}
|
|
|
|
const server = http.createServer(async (req, res) => {
|
|
if (req.method === "OPTIONS") {
|
|
res.writeHead(204, {
|
|
"Access-Control-Allow-Origin": "*",
|
|
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
|
"Access-Control-Allow-Headers": "Content-Type",
|
|
});
|
|
res.end();
|
|
return;
|
|
}
|
|
|
|
if (req.url === "/layout" && req.method === "GET") {
|
|
try {
|
|
const contents = await fs.promises.readFile(LAYOUT_PATH, "utf-8");
|
|
const json = JSON.parse(contents);
|
|
sendJson(res, 200, json);
|
|
} catch (err) {
|
|
sendJson(res, 500, { error: "Failed to read layout", detail: err.message });
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (req.url === "/layout" && req.method === "POST") {
|
|
let body = "";
|
|
req.on("data", (chunk) => {
|
|
body += chunk.toString();
|
|
if (body.length > 1_000_000) {
|
|
req.destroy();
|
|
}
|
|
});
|
|
req.on("end", async () => {
|
|
try {
|
|
const json = JSON.parse(body);
|
|
await fs.promises.writeFile(LAYOUT_PATH, JSON.stringify(json, null, 2));
|
|
sendJson(res, 200, { ok: true });
|
|
} catch (err) {
|
|
sendJson(res, 400, { error: "Invalid JSON", detail: err.message });
|
|
}
|
|
});
|
|
return;
|
|
}
|
|
|
|
sendText(res, 404, "Not found");
|
|
});
|
|
|
|
server.listen(PORT, () => {
|
|
console.log(`Layout config server listening on http://localhost:${PORT}`);
|
|
});
|