File size: 1,832 Bytes
d5b1062
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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
};