-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_queries.js
318 lines (270 loc) · 10.6 KB
/
db_queries.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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
// Load .env
require('dotenv').config();
// Constants
const { MONGODB_URI, MONGODB_DB_NAME } = require("./consts");
const { sumArray } = require("./utils");
var md5 = require('md5');
// Import mongodb package
const { MongoClient, ServerApiVersion } = require('mongodb');
// Variable that will hold the mongodb client object
const dbclient = new MongoClient(
MONGODB_URI,
{
serverApi: {
version: ServerApiVersion.v1
}
}
);
// Connects and tests the db connection
let initDatabaseConnection = async () => {
try{
await dbclient.connect();
await dbclient.db(MONGODB_DB_NAME).command({ ping: 1 });
console.log("[*] Database connection successful.");
}catch(e){
await dbclient.close();
console.error(e);
}
};
// Terminates the db connection
let closeDatabaseConnection = async () => {
try{
await dbclient.close();
}catch(e){
console.error(e);
}
};
const insertCurrencyRecords = async (newRecords, currency) => {
// Reconnect with the db
await dbclient.connect();
// Get the collection
const coll_currencyValues = dbclient.db(MONGODB_DB_NAME).collection("CurrencyValues");
const existingDbRecords = await coll_currencyValues.find({currency: currency.code}).toArray();
const existingDbRecordIDs = existingDbRecords.map(db_record => db_record._id);
// Add the db_id and data object that is going to be sent to the insertOne function, to the given each "newRecords" object
newRecords = newRecords.map((record) => {
const db_id = md5(JSON.stringify({
"timestamp": record.update_date,
"currency": currency.code,
"value": record.close
}));
const new_db_record = {
"_id": db_id,
"timestamp": new Date(record.update_date * 1000),
"currency": currency.code,
"value": record.close
};
return {
...record,
new_db_record: new_db_record
};
});
// Check if the id's for matching the records, find the existing and missing records.
const checkIfExistsOnDb = (record) => {
return existingDbRecordIDs.includes(record.new_db_record._id);
};
let final_existingRecords = newRecords.filter(checkIfExistsOnDb);
let final_newRecords = newRecords.filter((record) => !checkIfExistsOnDb(record));
console.log(`[*] Number of ${final_existingRecords.length} already exists for the currency ${currency.code}; adding ${final_newRecords.length} records!`);
// Insert the new records to the database
final_newRecords = final_newRecords.map(record => record.new_db_record);
if(final_newRecords.length > 0){
return await coll_currencyValues.insertMany(final_newRecords);
}
};
// Gets the given currency's current values held in DB
const getCurrencyValues = async (currencyCode) => {
// Reconnect with the db
await dbclient.connect();
// Get the collection
const coll_currencyValues = dbclient.db(MONGODB_DB_NAME).collection("CurrencyValues");
const result = await coll_currencyValues.find(
(
currencyCode
? {"currency": currencyCode}
: {}
)
).toArray();
return result;
};
// Gets the given currency's current values held in DB
const getCurrenciesToTrack = async (currencyCode) => {
// Reconnect with the db
await dbclient.connect();
// Get the collection
const coll_currenciesToTrack = dbclient.db(MONGODB_DB_NAME).collection("CurrenciesToTrack");
const result = await coll_currenciesToTrack.find({}).toArray();
return result;
};
// Gets the given currency's current values held in DB, dashboard format
const getAllCurrencyCurrentValues = async () => {
// Reconnect with the db
await dbclient.connect();
// Get the collections
const coll_currencyValues = dbclient.db(MONGODB_DB_NAME).collection("CurrencyValues");
const coll_currenciesToTrack = dbclient.db(MONGODB_DB_NAME).collection("CurrenciesToTrack");
let currencies = await (coll_currenciesToTrack.find({}).toArray());
currencies = await Promise.all(currencies.map(async (currency) => {
const currentCurrencyValues = await (coll_currencyValues.find(
{
currency: currency.code
},
{
sort: {timestamp: -1},
limit: 1
}
).toArray());
// Return null if no value exist for the currency
if(currentCurrencyValues.length === 0){
return {
...currency,
value: null,
timestamp: null
}
}
return {
...currency,
value: currentCurrencyValues[0].value,
timestamp: currentCurrencyValues[0].timestamp,
};
}));
return currencies;
};
// Check the user currency alerts, if they do match the criteria, return true.
const checkUserCurrencyAlerts = async () => {
console.log("[*] Checking currency alert triggers...");
// Reconnect with the db
await dbclient.connect();
// Get the collections
const coll_userCurrencyAlerts = dbclient.db(MONGODB_DB_NAME).collection("UserCurrencyAlerts");
let allUserCurrencyAlerts = await (coll_userCurrencyAlerts.find({}).toArray());
const coll_currencyValues = dbclient.db(MONGODB_DB_NAME).collection("CurrencyValues");
let now_timestamp = new Date();
let hrsago_timestamp = new Date(now_timestamp.getTime() - (3600 * parseInt(process.env.CALCULATE_LAST_AVERAGE_HOURS) * 1000));
let allCurrencyValues = await (coll_currencyValues.find({
timestamp: {
$gte: hrsago_timestamp,
$lt: now_timestamp
}
}).sort({timestamp: -1}).toArray());
// Check the alert criteria from the other collection
let allAlerts = allUserCurrencyAlerts.map((alert) => {
alert.messages = [];
alert.isTriggered = false;
// Skip the alert if it's already sent to the user
if(alert.isSentToUser) return alert;
// Get the currency records
const currentCurrencyValues = allCurrencyValues.filter((record) => (alert.currencyCode === record.currency));
if(currentCurrencyValues.length === 0) return alert;
let upToDateValueOfCurrency = currentCurrencyValues[0].value;
let leastUpToDateTimestamp = new Date(currentCurrencyValues[currentCurrencyValues.length-1].timestamp).getTime();
// Calculate the average value of current currency's records
let sumOfLastRecords = sumArray(currentCurrencyValues.map(x => x.value));
let upToDateAvgValueOfCurrency = (sumOfLastRecords / currentCurrencyValues.length)
let upToDateAvgHours = ((now_timestamp.getTime() - leastUpToDateTimestamp) / (3600 * 1000)).toFixed(2);
// Determine if the alert is gonna be triggered
if(alert.alertType === "exceed"){
if(upToDateValueOfCurrency > (alert.alertValue)){
alert.isTriggered = true;
alert.messages.push(
`${alert.currencyCode} dövizi, belirlediğiniz ${alert.alertValue.toFixed(2)} sınırını ${upToDateValueOfCurrency.toFixed(2)} olarak geçti!`
);
}
if(upToDateValueOfCurrency > (alert.alertValue * 1.10)){
alert.isTriggered = true;
alert.messages.push(
`${alert.currencyCode} dövizi, belirlediğiniz ${alert.alertValue.toFixed(2)} limitini %${
(((upToDateValueOfCurrency/alert.alertValue)-1)*100).toFixed(2)
} geçerek ${upToDateValueOfCurrency.toFixed(2)} oldu!`
);
}
if(upToDateValueOfCurrency > (upToDateAvgValueOfCurrency * 1.10)){
alert.isTriggered = true;
alert.messages.push(
`${alert.currencyCode} dövizi, son ${upToDateAvgHours} saat ortalaması olan ${upToDateAvgValueOfCurrency.toFixed(2)} değerinin %${
(((upToDateValueOfCurrency/upToDateAvgValueOfCurrency)-1)*100).toFixed(2)
} üstünde!`
);
}
}
// Update the alert's database record as "sent to user"
if(process.env.SEND_USER_TRIGGERS_ONLY_ONCE === "true" && alert.isTriggered){
coll_userCurrencyAlerts.updateOne(
{"_id": alert._id},
{$set: {
isSentToUser: true
}},
{upsert: false}
);
}
return alert;
});
// Filter the non-null values
let triggeredAlerts = allAlerts.filter(x => x.isTriggered);
if(triggeredAlerts.length > 0){
console.log("[*] Triggered alerts:");
console.log(triggeredAlerts);
}else{
console.log("[*] No alerts triggered.");
}
return triggeredAlerts;
}
const getUserCurrencyAlerts = async () => {
// Reconnect with the db
await dbclient.connect();
// Get the collections
const coll_userCurrencyAlerts = dbclient.db(MONGODB_DB_NAME).collection("UserCurrencyAlerts");
let allUserCurrencyAlerts = await (coll_userCurrencyAlerts.find({}).toArray());
return allUserCurrencyAlerts
};
const setUserCurrencyAlert = async (newAlertData) => {
try{
// Reconnect with the db
await dbclient.connect();
// Get the collections
const coll_userCurrencyAlerts = dbclient.db(MONGODB_DB_NAME).collection("UserCurrencyAlerts");
// "Upsert" the new records
await coll_userCurrencyAlerts.updateOne(
{
"currencyCode": newAlertData.currencyCode,
"alertType": newAlertData.alertType
},
{$set: newAlertData},
{upsert: true}
);
return true;
}catch(e){
return false;
}
};
const removeUserCurrencyAlert = async (removeAlertData) => {
try{
// Reconnect with the db
await dbclient.connect();
// Get the collections
const coll_userCurrencyAlerts = dbclient.db(MONGODB_DB_NAME).collection("UserCurrencyAlerts");
// Remove the specified records
await coll_userCurrencyAlerts.deleteMany(
{
"currencyCode": removeAlertData.currencyCode,
"alertType": removeAlertData.alertType
}
);
return true;
}catch(e){
return false;
}
};
module.exports = {
dbclient,
initDatabaseConnection,
closeDatabaseConnection,
insertCurrencyRecords,
getCurrencyValues,
getCurrenciesToTrack,
getAllCurrencyCurrentValues,
checkUserCurrencyAlerts,
getUserCurrencyAlerts,
setUserCurrencyAlert,
removeUserCurrencyAlert
}