91 lines
2.7 KiB
JavaScript
91 lines
2.7 KiB
JavaScript
const { createServer } = require("http");
|
|
const next = require("next");
|
|
const { Server } = require("socket.io");
|
|
const fs = require("fs");
|
|
const path = require("path");
|
|
const fetch = (...args) => import("node-fetch").then(({ default: fetch }) => fetch(...args));
|
|
|
|
const dev = process.env.NODE_ENV !== "production";
|
|
const app = next({ dev });
|
|
const handle = app.getRequestHandler();
|
|
const PORT = 3000;
|
|
|
|
app.prepare().then(() => {
|
|
const server = createServer((req, res) => {
|
|
handle(req, res);
|
|
});
|
|
|
|
const io = new Server(server);
|
|
|
|
io.on("connection", socket => {
|
|
const { m, mode } = socket.handshake.query;
|
|
const idMap = m;
|
|
const isLiveMode = mode === "live" || mode === "prod";
|
|
|
|
let lastStatis = [];
|
|
|
|
const fetchData = async () => {
|
|
try {
|
|
let statis;
|
|
|
|
if (dev) {
|
|
const mockPath = path.join(process.cwd(), "mockData", "GisLinesStatus.json");
|
|
const jsonStr = fs.readFileSync(mockPath, "utf-8");
|
|
const json = JSON.parse(jsonStr);
|
|
statis = json?.Statis || [];
|
|
console.log("🧪 Mockdaten gelesen");
|
|
} else {
|
|
const fetchUrl = `http://localhost/talas5/ClientData/WebServiceMap.asmx/GisLinesStatus?idMap=${idMap}`;
|
|
const res = await fetch(fetchUrl);
|
|
const text = await res.text();
|
|
|
|
if (!text.startsWith("{")) {
|
|
console.error("❌ Webservice liefert kein valides JSON:", text.slice(0, 100));
|
|
return;
|
|
}
|
|
|
|
const json = JSON.parse(text);
|
|
statis = json?.Statis || [];
|
|
console.log("📡 Webservice-Daten empfangen");
|
|
}
|
|
|
|
const hasChanged =
|
|
statis.length !== lastStatis.length ||
|
|
statis.some((entry, index) => {
|
|
const prev = lastStatis[index];
|
|
return (
|
|
!prev ||
|
|
entry.Modul !== prev.Modul ||
|
|
entry.ModulName !== prev.ModulName ||
|
|
entry.Value !== prev.Value ||
|
|
entry.Level !== prev.Level
|
|
);
|
|
});
|
|
|
|
if (hasChanged) {
|
|
lastStatis = statis;
|
|
socket.emit("gisLinesStatusUpdated", statis);
|
|
console.log("✅ Änderung erkannt und gesendet");
|
|
} else {
|
|
console.log("🔁 Keine Änderung festgestellt");
|
|
}
|
|
} catch (error) {
|
|
console.error("❌ Fehler beim Datenabruf:", error.message);
|
|
}
|
|
};
|
|
|
|
if (isLiveMode) {
|
|
fetchData();
|
|
const interval = setInterval(fetchData, 5000);
|
|
socket.on("disconnect", () => {
|
|
clearInterval(interval);
|
|
console.log("❌ WebSocket getrennt");
|
|
});
|
|
}
|
|
});
|
|
|
|
server.listen(PORT, () => {
|
|
console.log(`🚀 App + Socket.io läuft auf http://localhost:${PORT}`);
|
|
});
|
|
});
|