ulduldp commited on
Commit
d5b1062
·
verified ·
1 Parent(s): 9e74aaf

Create services/pinger.service.js

Browse files
Files changed (1) hide show
  1. services/pinger.service.js +95 -0
services/pinger.service.js ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const axios = require("axios");
2
+ const db = require("../storage/db");
3
+ const cache = require("../storage/cache");
4
+
5
+ const MAX_HISTORY = 100;
6
+
7
+ function getPingers() {
8
+ let data = cache.get("pingers");
9
+ if (!data) {
10
+ data = db.read("pingers.json");
11
+ cache.set("pingers", data);
12
+ }
13
+ return data;
14
+ }
15
+
16
+ function savePingers(data) {
17
+ db.write("pingers.json", data);
18
+ cache.set("pingers", data);
19
+ }
20
+
21
+ function getLogs() {
22
+ let data = cache.get("logs");
23
+ if (!data) {
24
+ data = db.read("logs.json");
25
+ cache.set("logs", data);
26
+ }
27
+ return data;
28
+ }
29
+
30
+ function saveLogs(data) {
31
+ db.write("logs.json", data);
32
+ cache.set("logs", data);
33
+ }
34
+
35
+ async function ping(pinger) {
36
+ const start = Date.now();
37
+ let status = "DOWN";
38
+ let latency = 0;
39
+
40
+ try {
41
+ const res = await axios({
42
+ url: pinger.url,
43
+ method: pinger.method,
44
+ timeout: pinger.timeout * 1000,
45
+ headers: pinger.headers,
46
+ data: pinger.body
47
+ });
48
+
49
+ latency = Date.now() - start;
50
+ status = res.status < 400 ? "UP" : "DOWN";
51
+
52
+ } catch (err) {
53
+ latency = Date.now() - start;
54
+ status = "DOWN";
55
+ }
56
+
57
+ updateLogs(pinger, status, latency);
58
+ }
59
+
60
+ function updateLogs(pinger, status, latency) {
61
+ const logs = getLogs();
62
+
63
+ if (!logs[pinger.id]) logs[pinger.id] = [];
64
+
65
+ logs[pinger.id].push({
66
+ time: new Date().toISOString(),
67
+ status,
68
+ latency
69
+ });
70
+
71
+ if (logs[pinger.id].length > MAX_HISTORY) {
72
+ logs[pinger.id].shift();
73
+ }
74
+
75
+ saveLogs(logs);
76
+
77
+ // update pinger status
78
+ const pingers = getPingers();
79
+ const index = pingers.findIndex(p => p.id === pinger.id);
80
+
81
+ if (index !== -1) {
82
+ pingers[index].status = status;
83
+ pingers[index].latency = latency;
84
+ pingers[index].lastUpdated = new Date().toISOString();
85
+ savePingers(pingers);
86
+ }
87
+ }
88
+
89
+ module.exports = {
90
+ getPingers,
91
+ savePingers,
92
+ getLogs,
93
+ saveLogs,
94
+ ping
95
+ };