Spaces:
Paused
Paused
| const axios = require("axios"); | |
| const db = require("../storage/db"); | |
| const cache = require("../storage/cache"); | |
| const MAX_HISTORY = 100; | |
| function getPingers() { | |
| let data = cache.get("pingers"); | |
| if (!data) { | |
| data = db.read("pingers.json"); | |
| cache.set("pingers", data); | |
| } | |
| return data; | |
| } | |
| function savePingers(data) { | |
| db.write("pingers.json", data); | |
| cache.set("pingers", data); | |
| } | |
| function getLogs() { | |
| let data = cache.get("logs"); | |
| if (!data) { | |
| data = db.read("logs.json"); | |
| cache.set("logs", data); | |
| } | |
| return data; | |
| } | |
| function saveLogs(data) { | |
| db.write("logs.json", data); | |
| cache.set("logs", data); | |
| } | |
| async function ping(pinger) { | |
| const start = Date.now(); | |
| let status = "DOWN"; | |
| let latency = 0; | |
| try { | |
| const res = await axios({ | |
| url: pinger.url, | |
| method: pinger.method, | |
| timeout: pinger.timeout * 1000, | |
| headers: pinger.headers, | |
| data: pinger.body | |
| }); | |
| latency = Date.now() - start; | |
| status = res.status < 400 ? "UP" : "DOWN"; | |
| } catch (err) { | |
| latency = Date.now() - start; | |
| status = "DOWN"; | |
| } | |
| updateLogs(pinger, status, latency); | |
| } | |
| function updateLogs(pinger, status, latency) { | |
| const logs = getLogs(); | |
| if (!logs[pinger.id]) logs[pinger.id] = []; | |
| logs[pinger.id].push({ | |
| time: new Date().toISOString(), | |
| status, | |
| latency | |
| }); | |
| if (logs[pinger.id].length > MAX_HISTORY) { | |
| logs[pinger.id].shift(); | |
| } | |
| saveLogs(logs); | |
| // update pinger status | |
| const pingers = getPingers(); | |
| const index = pingers.findIndex(p => p.id === pinger.id); | |
| if (index !== -1) { | |
| pingers[index].status = status; | |
| pingers[index].latency = latency; | |
| pingers[index].lastUpdated = new Date().toISOString(); | |
| savePingers(pingers); | |
| } | |
| } | |
| module.exports = { | |
| getPingers, | |
| savePingers, | |
| getLogs, | |
| saveLogs, | |
| ping | |
| }; |