-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathalerts.js
84 lines (73 loc) · 2 KB
/
alerts.js
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
const axios = require('axios');
const express = require('express');
const config = require('./config');
const summits = require('./summits');
let router = express.Router();
module.exports = router;
let alertCache = [];
let lastLoadDate;
let pendingLoad;
router.get('/', (req, res) => {
res.cacheControl = {
noCache: true
};
loadAlerts(req.query.noCache)
.then(alerts => {
res.json(alerts);
})
.catch(err => {
console.error(err);
res.status(500).end();
})
});
function loadAlerts(noCache) {
if (noCache) {
console.log('Load alerts (no cache)');
return loadAlertsDirect();
}
if (lastLoadDate && (new Date() - lastLoadDate) < config.alerts.minUpdateInterval) {
return Promise.resolve(alertCache);
}
if (!pendingLoad) {
console.log('Load alerts (cache)');
pendingLoad = loadAlertsDirect()
.then(response => {
pendingLoad = null;
return response;
})
.catch(err => {
pendingLoad = null;
return Promise.reject(err);
})
}
return pendingLoad;
}
function loadAlertsDirect() {
// TODO: check epoch and only load alerts list if the epoch has changed since the last load
return axios.get(config.alerts.url)
.then(response => {
if (response.status !== 200) {
console.error(`Got status ${response.status} when loading alerts`);
return Promise.reject('Cannot load alerts from SOTAwatch');
}
let newAlerts = response.data.map(alert => {
return {
id: alert.id,
userID: alert.userID,
timeStamp: new Date(alert.timeStamp),
dateActivated: new Date(alert.dateActivated),
summit: {code: alert.associationCode + '/' + alert.summitCode},
activatorCallsign: alert.activatingCallsign.toUpperCase().replace(/[^A-Z0-9\/-]/g, ''),
posterCallsign: alert.posterCallsign,
frequency: alert.frequency,
comments: alert.comments !== '(null)' ? alert.comments : ''
};
});
return summits.lookupSummits(newAlerts)
.then(alerts => {
alertCache = alerts;
lastLoadDate = new Date();
return alerts;
});
})
}