grist-data-gateway/gateway.cjs

47 lines
1.7 KiB
JavaScript

const http = require("http");
const Redis = require("ioredis");
const redis = new Redis({ host: process.env.REDIS_HOST || "data_jobs",
port: Number(process.env.REDIS_PORT || 6379) });
const JOBS = process.env.JOB_QUEUE || "grist:jobs";
const RESULTS = process.env.RESULT_QUEUE || "grist:results";
http.createServer(async (req, res) => {
if (req.method === "POST" && req.url === "/api/job") {
const stream = await readJsonBody(req); // JSON Stream vom Client. mit readJsonBody() wieder zurück in JSON.
await redis.lpush(JOBS, JSON.stringify(stream)); // Job in Queue. Als String in Redis eintragen. Der Worker nimmt dann den String.
const reply = await redis.blpop(RESULTS, 30); // auf Antwort warten
const value = reply[1]; // Worker-Response
res.writeHead(200, {"content-type":"application/json"});
try {
JSON.parse(value); res.end(value); //Prüfen für JSON
} catch {
res.end(JSON.stringify({ //Fallback damit es sicher ein JSON ist.
ok:true,
data:value
}));
}
}
//mit curl http://192.168.0.104:8080/health kann man checken ob das Gateway überhaupt arbeitet.
if (req.method === "GET" && req.url === "/health") {
res.writeHead(200, { "content-type":"text/plain" });
return res.end("ok");
}
res.writeHead(404, { "content-type":"text/plain" });
res.end("not found");
}).listen(8080, "0.0.0.0", () => console.log("[gateway] listening 8080"));
//DataStream in Json zurückverwandeln.
function readJsonBody(req){
return new Promise((resolve) => {
let buf = "";
req.on("data", c => buf += c);
req.on("end", () => resolve(buf ? JSON.parse(buf) : null));
});
}