-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueries.js
451 lines (422 loc) · 13.6 KB
/
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
const promise = require('bluebird');
const options = {
// Initialization Options
promiseLib: promise,
error(error, e) {
if (e.cn) {
// A connection-related error;
//
// Connections are reported back with the password hashed,
// for safe errors logging, without exposing passwords.
console.log('CN:', e.cn);
console.log('EVENT:', error.message || error);
}
}
};
const pgp = require('pg-promise')(options);
const connectionString = 'postgres://ygqngyntmnkayw:178f3e5a336d2a687d17e822bff111c69333ee122bf6c95a691822b034bbe696@ec2-54-235-178-189.compute-1.amazonaws.com:5432/def5sl55fh28j5?ssl=true';
const db = pgp(connectionString);
function getAllUsers(req, res, next)
{
return searchUser(req,res,next);
}
function getUserByID(req, res, next)
{
const userID = parseInt(req.params.id);
db.one('select * from users where id = $1', userID)
.then(function (data)
{
res.status(200)
.json({
status: 'success',
data: data
});
})
.catch(function (err)
{
if(err.message==="No data returned from the query.")
return next("There is not costumer with the given ID");
return next(err);
});
}
async function isEmailAlreadyExist(email)
{
const r= await db.any('select * from users where email = $1', email).then(function (data)
{
return data.length>0;
}).catch(function (err)
{
console.log(err);
return false;
});
return r;
}
async function createUser(req, res, next)
{
if (req.body.second_name===undefined)
{
req.body.second_name="";
}
if(!validateEmail(req.body.email))
{
return next("Email format incorrect");
}
const v=await isEmailAlreadyExist(req.body.email);
console.log(v);
if(v)
{
return next("Email already registered");
}
db.none('insert into users (first_name, second_name, first_surname, second_surname,email) '+
"VALUES (${first_name}, ${second_name}, ${first_surname}, ${second_surname}, ${email})",
req.body)
.then(function ()
{
db.one('SELECT * FROM users ORDER BY ID DESC LIMIT 1')
.then(function (data)
{
res.status(200)
.json({
status: 'success',
data: data
});
})
.catch(function (err)
{
console.log(err);
return next(err);
});
})
.catch(function (err)
{
console.log(err);
return next(err.message);
});
}
async function updateUser(req, res, next)
{
const userID = parseInt(req.params.id);
if(req.body.email!==undefined&&!validateEmail(req.body.email))
{
return next("Email format incorrect");
}
const v=await isEmailAlreadyExist(req.body.email);
if(req.body.email!==undefined&&v)
{
return next("Email already registered");
}
db.one('select * from users where id = $1', userID)
.then(function (data)
{
req.body.first_name=req.body.first_name||data.first_name;
req.body.second_name=req.body.second_name||data.second_name;
req.body.first_surname=req.body.first_surname||data.first_surname;
req.body.second_surname=req.body.second_surname||data.second_surname;
req.body.email=req.body.email||data.email;
db.none('update users set first_name=$1, second_name=$2, first_surname=$3, second_surname=$4, email=$5' +
' where id=$6',
[req.body.first_name, req.body.second_name, req.body.first_surname, req.body.second_surname,
req.body.email, parseInt(req.params.id)])
.then(function ()
{
res.status(200)
.json({
status: 'success',
message: req.body
});
})
.catch(function (err)
{
return next(err);
});
})
.catch(function (err)
{
if(err.message==="No data returned from the query.")
return next("There is not costumer with the given ID");
return next(err);
});
}
function removeUser(req, res, next)
{
const userID = parseInt(req.params.id);
db.result('delete from users where id = $1', userID)
.then(async function (result)
{
await removeAllTransactionsOfUser(req,res,next,userID);
res.status(200)
.json({
status: 'success',
message: `Removed ${result.rowCount} user`
});
})
.catch(function (err)
{
return next(err);
});
}
async function removeAllTransactionsOfUser(req, res, next, id)
{
await db.result('delete from transactions where customer = $1', id)
.then(function (result)
{
})
.catch(function (err)
{
return next(err);
});
}
function searchUser(req, res, next)
{
const first_name = req.query.first_name;
const second_name = req.query.second_name;
const first_surname = req.query.first_surname;
const second_surname = req.query.second_surname;
const email = req.query.email;
let qu='select * from users' +
' where LOWER(first_name) like LOWER('+"'%"+(first_name||"")+"%'"+')'+
'and LOWER(second_name) like LOWER('+"'%"+(second_name||"")+"%'"+')'+
'and LOWER(first_surname) like LOWER('+"'%"+(first_surname||"")+"%'"+')'+
'and LOWER(second_surname) like LOWER('+"'%"+(second_surname||"")+"%'"+')'+
'and LOWER(email) like LOWER('+"'%"+(email||"")+"%'"+')';
db.any(qu)
.then(function (data)
{
res.status(200)
.json({
status: 'success',
data: data,
});
})
.catch(function (err)
{
return next(err);
});
}
async function getCustomerString(req, res, next, id)
{
const r = db.one('select * from users where id = $1', id)
.then(function (data)
{
return data;
})
.catch(function (err)
{
return next(err);
});
return r;
}
function getAllTransactions(req, res, next)
{
return searchTransaction(req,res,next);
}
function getTransactionByID(req, res, next)
{
const userID = parseInt(req.params.id);
db.one('select * from transactions where id = $1', userID)
.then(async function (data)
{
data.customer=await getCustomerString(req,res,next,data.customer);
res.status(200)
.json({
status: 'success',
data: data
});
})
.catch(function (err)
{
if(err.message==="No data returned from the query.")
return next("There is not transactions with the given ID");
return next(err);
});
}
function getTransactionByUserID(req, res, next)
{
const userID = parseInt(req.params.id);
db.any('select * from transactions where customer = $1', userID)
.then(async function (data)
{
const customerData=await getCustomerString(req,res,next,userID);
for(let i=0;i<data.length;i++)
{
data[i].customer=customerData;
}
res.status(200)
.json({
status: 'success',
data: data
});
})
.catch(function (err)
{
if(err.message==="No data returned from the query.")
return next("There is not transactions with the given customer ID");
console.log(err);
return next(err);
});
}
function createATransaction(req, res, next)
{
if (req.body.date === undefined)
{
req.body.date = new Date();
}
if(req.body.customer===undefined)
{
return next("A customer ID is required");
}
db.one('select * from users where id = $1', parseInt(req.body.customer))
.then(function (dat)
{
db.none('insert into transactions (customer, date, amount) '+
"VALUES (${customer}, ${date}, ${amount})",
req.body)
.then(function ()
{
db.one('SELECT * FROM transactions ORDER BY ID DESC LIMIT 1')
.then(function (data)
{
data.customer=dat;
res.status(200)
.json({
status: 'success',
data: data
});
})
.catch(function (err)
{
return next(err);
});
})
.catch(function (err)
{
return next(err.message);
});
})
.catch(function (err)
{
if(err.message==="No data returned from the query.")
return next("There is not costumer with the given ID");
return next(err);
});
}
function updateTransactions(req, res, next)
{
const userID = parseInt(req.params.id);
db.one('select * from transactions where id = $1', userID)
.then(function (data)
{
req.body.customer=req.body.customer||data.customer;
req.body.date=req.body.date!==undefined?new Date(req.body.date):data.date;
req.body.amount=req.body.amount||data.amount;
db.one('select * from users where id = $1', parseInt(req.body.customer))
.then(function (dat)
{
db.none('update transactions set customer=$1, date=$2, amount=$3' +
' where id=$4',
[req.body.customer, req.body.date, req.body.amount, parseInt(req.params.id)])
.then(function ()
{
req.body.customer=dat;
res.status(200)
.json({
status: 'success',
message: req.body
});
})
.catch(function (err)
{
return next(err);
});
}).catch(function (err)
{
if(err.message==="No data returned from the query.")
return next("There is not costumer with the given ID");
return next(err);
});
})
.catch(function (err)
{
if(err.message==="No data returned from the query.")
return next("There is not transactions with the given ID");
return next(err);
});
}
function removeTransaction(req, res, next)
{
const userID = parseInt(req.params.id);
db.result('delete from transactions where id = $1', userID)
.then(function (result)
{
res.status(200)
.json({
status: 'success',
message: `Removed ${result.rowCount} transaction`
});
})
.catch(function (err)
{
return next(err);
});
}
function searchTransaction(req, res, next)
{
const customer = req.query.customer;
const date = req.query.date||"";
const amount = req.query.amount||"";
let qu;
if(customer!==undefined)
{
qu='select * from transactions' +
' where customer='+customer+
' and TO_CHAR(date,\'dd.mm.yyyy\') LIKE '+"'%"+date+"%'"+
' and CAST(amount AS VARCHAR(20)) like '+"'%"+amount+"%'";
}
else
{
qu='select * from transactions' +
' where'+
' TO_CHAR(date,\'dd.mm.yyyy\') LIKE '+"'%"+date+"%'"+
' and CAST(amount AS VARCHAR(20)) like '+"'%"+amount+"%'";
}
db.any(qu)
.then(async function (data)
{
for(let i=0;i<data.length;i++)
{
data[i].customer=await getCustomerString(req,res,next,data[i].customer);
}
res.status(200)
.json({
status: 'success',
data: data,
});
})
.catch(function (err)
{
console.log(err);
return next(err);
});
}
function validateEmail(email) {
const REGEXP = new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
email = email.trim();
if(REGEXP.test(email)) {
return true;
}
console.error('Invalid email. ');
return false;
}
module.exports = {
getAllUsers: getAllUsers,
getUserByID: getUserByID,
createUser: createUser,
updateUser: updateUser,
removeUser: removeUser,
getAllTransactions: getAllTransactions,
getTransactionByID:getTransactionByID,
createATransaction: createATransaction,
updateTransactions: updateTransactions,
removeTransaction: removeTransaction,
getTransactionByUserID: getTransactionByUserID,
};