-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
157 lines (134 loc) · 5.32 KB
/
index.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
// Load .env
require('dotenv').config();
// Import express.js
const express = require('express');
const cors = require('cors');
// Import websocket
const { WebSocketServer } = require('ws');
// Import cron for periodically syncing with doviz.com
const cron = require('node-cron');
/// Import local functions
// Doviz.com queries
const { getCurrencyDataDaily, getCurrencyDataLive, checkDovizComAuth, updateDovizComAuth } = require("./dovizcom_queries");
// Methods and objects related to our database operations
const {
dbclient,
initDatabaseConnection,
closeDatabaseConnection,
insertCurrencyRecords,
getCurrenciesToTrack,
getCurrencyValues,
getAllCurrencyCurrentValues,
checkUserCurrencyAlerts,
getUserCurrencyAlerts,
setUserCurrencyAlert,
removeUserCurrencyAlert
} = require("./db_queries");
// Synchronizes doviz.com data
const synchronizeExchangeData = async (pullDovizComDataFn) => {
// Get all the currencies from OUR database, it specifies which currencies to track on doviz.com
const currencies = await getCurrenciesToTrack();
// Query and process each currency data from doviz.com
for(let cIdx=0; cIdx <= currencies.length-1; cIdx++){
let currency = currencies[cIdx];
let response = pullDovizComDataFn(currency);
if(response.error === true){
console.error("[!] Doviz.com auth error, refreshing auth..");
// Re-run the sync function after renewing the auth token
updateDovizComAuth().then((isAuthSuccessful) => {
if(isAuthSuccessful){
synchronizeExchangeData(pullDovizComDataFn);
}
});
return false;
}else{
let dovizComSourceData = response.data;
dovizComSourceData = dovizComSourceData.filter((record) => {
let now_timestamp = new Date().getTime() / 1000;
let xhrsago_timestamp = (now_timestamp - (3600 * parseInt(process.env.DOVIZCOM_PULL_MAX_X_HOURS_OF_HISTORY)));
if(record.update_date >= xhrsago_timestamp){
return true;
}
return false;
});
// Process the each record of the currency query
console.log(`[*] Pulled number of ${dovizComSourceData.length} records from doviz.com for the currency ${currency.code}...`);
await insertCurrencyRecords(dovizComSourceData, currency);
}
}
console.log("[*] synchronizeExchangeData function run done.");
return true;
};
// Build the web serving application and serve it
const app = express();
// Setup the alert system through websocket
const wss = new WebSocketServer({port: process.env.WS_PORT});
// Set the websocket connection functions.
wss.on('connection', (ws) => {
// Trigger the user alert checking functionality here
const triggerCheckingUserCurrencyAlerts = async () => {
let triggeredAlerts = await checkUserCurrencyAlerts();
if(triggeredAlerts.length > 0){
ws.send(JSON.stringify(triggeredAlerts));
}
};
// Set an interval for running triggerCheckingUserCurrencyAlerts periodically
console.log("[*] WebSocket connected");
let interval_triggerCheckingUserCurrencyAlerts = setInterval(
triggerCheckingUserCurrencyAlerts,
(parseInt(process.env.DOVIZCOM_PULL_LIVE_DATA_EVERY_XMINUTES) * 30 * 1000)
);
ws.on('close', () => {
clearInterval(interval_triggerCheckingUserCurrencyAlerts);
interval_triggerCheckingUserCurrencyAlerts = null;
console.log("[*] Terminating the WebSocket connection");
});
});
app.use(express.json());
// Add the extra middlewares.
app.use(cors());
// API endpoints of our backend-side server application
app.get('/getAllCurrencyCurrentValues', async (req, res) => {
res.send(await getAllCurrencyCurrentValues());
})
app.get('/getCurrencyValues', async (req, res) => {
res.send(await getCurrencyValues());
})
app.get('/getCurrenciesToTrack', async (req, res) => {
res.send(await getCurrenciesToTrack());
})
app.get('/synchronizeExchangeData', async (req, res) => {
res.send(await synchronizeExchangeData(getCurrencyDataDaily));
})
app.get('/getUserCurrencyAlerts', async (req, res) => {
res.send(await getUserCurrencyAlerts());
})
app.post('/setUserCurrencyAlert', async (req, res) => {
res.send(await setUserCurrencyAlert(req.body));
})
app.post('/removeUserCurrencyAlert', async (req, res) => {
res.send(await removeUserCurrencyAlert(req.body));
})
app.listen(
process.env.PORT,
async () => {
console.log(`[*] Express app is running on port ${process.env.PORT}!`);
await initDatabaseConnection();
console.log("[*] Checking doviz.com auth...");
while(!checkDovizComAuth()){
console.error("[!] Doviz.com auth failed, refreshing auth...");
await updateDovizComAuth();
};
console.log("[+] Doviz.com auth valid!");
await synchronizeExchangeData(getCurrencyDataDaily);
// Set cron schedules.
cron.schedule(
`*/${
process.env.DOVIZCOM_PULL_LIVE_DATA_EVERY_XMINUTES
? process.env.DOVIZCOM_PULL_LIVE_DATA_EVERY_XMINUTES
: '1'
} * * * *`,
() => synchronizeExchangeData(getCurrencyDataLive)
);
}
);