sozday-mne-dashbord-dannyh-s/server.js

105 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 COLUMNS = ["name", "district", "households", "connected"];
let cache = { ts: 0, data: null };
const TTL = 60000;
async function chQuery(sql) {
if (!process.env.CH_BASE_URL || !process.env.CH_API_KEY) throw new Error("ClickHouse не подключён");
const r = await fetch(process.env.CH_BASE_URL + "/query", {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: "Bearer " + process.env.CH_API_KEY },
body: JSON.stringify({ sql, max_rows: 500 })
});
const j = await r.json();
if (!j.ok) throw new Error(j.error || "ClickHouse ошибка");
return j;
}
async function getSatellite() {
if (cache.data && Date.now() - cache.ts < TTL) return cache.data;
let data;
if (process.env.CH_BASE_URL && process.env.CH_API_KEY) {
try {
const j = await chQuery(
`SELECT aul AS name, district, count() AS households, countIf(connected = 1) AS connected
FROM satellite_connections WHERE region = 'Павлодарская область'
GROUP BY aul, district ORDER BY aul ASC LIMIT 100`
);
const rows = (j.data || []).map((r) => {
const o = {};
j.meta.forEach((m, i) => { o[m.name] = r[i]; });
return { name: o.name, district: o.district || "", households: Number(o.households) || 0, connected: Number(o.connected) || 0 };
});
if (rows.length) {
data = { live: true, source: "ClickHouse (база предприятия)", aules: rows };
cache = { ts: Date.now(), data };
return data;
}
} catch (e) {
data = { live: false, source: "ClickHouse (данных нет, показаны демо-значения)", aules: null, _chError: String(e.message || e) };
}
}
if (!data) {
const d = JSON.parse(fs.readFileSync(DATA_FILE, "utf8"));
d.live = false;
if (process.env.CH_BASE_URL) d.source = "demo (ClickHouse подключён, но таблица не найдена)";
else d.source = "demo (демонстрационные данные)";
data = d;
}
cache = { ts: Date.now(), data };
return data;
}
const MIME = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".svg": "image/svg+xml",
".png": "image/png",
".ico": "image/x-icon",
".woff2": "font/woff2"
};
const server = http.createServer(async (req, res) => {
const url = req.url.split("?")[0];
try {
if (req.method === "GET" && url === "/api/satellite") {
const data = await getSatellite();
if (data._chError) console.log("[ch] " + data._chError);
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
return res.end(JSON.stringify(data));
}
if (req.method === "GET" && url === "/api/satellite.csv") {
const data = await getSatellite();
const lines = [COLUMNS.join(",")];
for (const a of data.aules || []) {
lines.push([a.name, '"' + String(a.district) + '"', a.households, a.connected].join(","));
}
res.writeHead(200, { "Content-Type": "text/csv; charset=utf-8", "Content-Disposition": 'attachment; filename="satellite-pavlodar.csv"' });
return res.end("\uFEFF" + lines.join("\n"));
}
let file = url === "/" ? "/index.html" : url;
const full = path.join(__dirname, path.normalize(file));
if (full.startsWith(__dirname) && fs.existsSync(full) && fs.statSync(full).isFile()) {
res.writeHead(200, { "Content-Type": (MIME[path.extname(full)] || "application/octet-stream") , "Cache-Control": "no-store" });
return res.end(fs.readFileSync(full));
}
res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
res.end("Not found");
} catch (e) {
console.error("Ошибка:", e);
res.writeHead(500, { "Content-Type": "application/json; charset=utf-8" });
res.end(JSON.stringify({ ok: false, error: String(e.message || e) }));
}
});
server.listen(PORT, () => console.log("Сервер на порту " + PORT + (process.env.CH_BASE_URL ? ", ClickHouse подключён" : ", ClickHouse не подключён — демо-данные")));