-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.postgres.js
1058 lines (973 loc) · 31.2 KB
/
app.postgres.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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const path = require('path');
require("dotenv").config();
//const cors = require('cors');
const express = require("express");
const server = express();
const { pool } = require("./dbConfig.postgres");
const bcrypt = require("bcrypt");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const passport = require("passport");
const saltRounds = 10;
const PORT = process.env.PORT || 4000;
server.set("view engine", "ejs");
// var whitelist = [
// 'http://localhost:3002',
// 'http://localhost:3000']; //white list consumers
// var corsOptions = {
// origin: function (origin, callback) {
// if (whitelist.indexOf(origin) !== -1) {
// callback(null, true);
// } else {
// callback(null, false);
// }
// },
// methods: ['GET', 'PUT', 'POST', 'PATCH', 'DELETE', 'OPTIONS'],
// optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
// credentials: true, //Credentials are cookies, authorization headers or TLS client certificates.
// allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'device-remember-token', 'Access-Control-Allow-Origin', 'Origin', 'Accept']
// };
// server.use(cors(corsOptions)); //add cors middleware to express with above configuration
server.use(express.urlencoded({ extended: true }));
server.use(express.json());
server.use(
session({
secret: "secret",
resave: false,
saveUninitialized: false,
sameSite: "none",
cookie: { httpOnly: false },
})
);
server.use(passport.initialize());
server.use(passport.session());
require(`./passportConfig`)(passport);
var router = express.Router({mergeParams: true});
server.use(router);
router.use(express.static(path.join(__dirname, 'build')));
server.get("/", (req, res) => {
return res.status;
});
router.get("/todos/all", async (req, res) => {
const response = await pool.query(`SELECT * FROM todos`);
if (Boolean(response.rows)) {
return res.status(200).send(response.rows);
}
return res.status(404);
});
router.post("/todos/create", async (req, res) => {
try {
let {
title,
description,
createdDate,
category,
priority,
} = req.body;
await pool.query(`INSERT INTO todos (title, description, createdDate, category, priority)
VALUES ($1, $2, $3, $4, $5) RETURNING id, title, description, createdDate, category, priority`, [title, description, createdDate, category, priority],
(err, result) => {
if (err) {
console.error(`\ntodosCreate failed with error: `, err.message);
let msg = err.message;
return res.status(500).send(msg);
}
if (result.rowCount === 0) {
let msg = "rowCount returned 0";
return res.status(406).send(msg);
}
else {
return res.status(200).send(result.rows[0]);
}
});
return res.status;
} catch (error) {
return error;
}
});
router.post("/todos/update", async (req, res) => {
try {
const {
id,
title,
description,
createdDate,
category,
priority,
} = req.body;
await pool.query( `UPDATE todos SET title=$2, description=$3, category=$5, priority=$6 WHERE todos.id = $1 RETURNING id, title, description, createdDate, category, priority`, [id, title, description, createdDate, category, priority],
(err, results) => {
if (err) {
let msg = err.message;
return res.status(409).send({msg});
} else {
let msg = results.rowCount;
return res.status(200).send({msg});
}
});
} catch (error) {
return error;
}
});
router.post("/todos/delete", async (req, res) => {
try {
let id = req.body.id;
await pool.query(`DELETE from todos WHERE todos.id = $1 RETURNING id`, [id],
(err, results) => {
if (err) {
let msg = err.message;
return res.status(409).send({msg});
} else {
let msg = results;
return res.status(200).send({msg});
}
});
} catch (error) {
return error;
}
});
router.get("/events/all", async (req, res) => {
try {
const response = await pool.query(`SELECT id, start, end, until, occurrenceId, title, description, category, priority, allDay, done, interval, every, Sun, Mon, Tue, Wed, Thu, Fri, Sat FROM events`);
if (Boolean(response.rows)) {
return res.status(200).send(response.rows);
}
return res.status(404);
} catch (error) {
return error;
}
});
router.post("/events/create", async (req, res) => {
try {
let {
start,
end,
until,
occurrenceId,
title,
description,
category,
priority,
allDay,
done,
interval,
every,
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
} = req.body;
await pool.query(`INSERT INTO events (start, end, until, occurrenceId, title, description, category, priority, allDay, done, interval, every, Sun, Mon, Tue, Wed, Thu, Fri, Sat)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19) RETURNING id, start, end, until, occurrenceId, title, description, category, priority, allDay, done, interval, every, Sun, Mon, Tue, Wed, Thu, Fri, Sat`, [start, end, until, occurrenceId, title, description, category, priority, allDay, done, interval, every, Sun, Mon, Tue, Wed, Thu, Fri, Sat],
(err, result) => {
if (err) {
let msg = err.message;
return res.status(500).send(msg);
}
if (result.rowCount === 0) {
let msg = "rowCount returned 0";
return res.status(406).send(msg);
}
else {
return res.status(200).send(result.rows[0]);
}
});
return res.status;
} catch (error) {
return error;
}
});
router.post("/events/update", async (req, res) => {
try {
const {
start,
end,
until,
occurrenceId,
title,
description,
category,
priority,
allDay,
done,
interval,
every,
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat,
id
} = req.body;
await pool.query( `UPDATE events SET start=$1, end=$2, until=$3, occurrenceId=$4, title=$5, description=$6, category=$7, priority=$8, allDay=$9, done=$10, interval=$11, every=$12, Sun=$13, Mon=$14, Tue=$15, Wed=$16, Thu=$17, Fri=$18, Sat=$19 WHERE events.id = $20 RETURNING id, start, end, until, occurrenceId, title, description, category, priority, allDay, done, interval, every, Sun, Mon, Tue, Wed, Thu, Fri, Sat `, [start, end, until, occurrenceId, title, description, category, priority, allDay, done, interval, every, Sun, Mon, Tue, Wed, Thu, Fri, Sat, id],
(err, results) => {
if (err) {
let msg = err.message;
return res.status(409).send({msg});
} else {
let msg = results.rowCount;
return res.status(200).send({msg});
}
});
} catch (error) {
return error;
}
});
router.post("/events/delete", async (req, res) => {
try {
let id = req.body.id;
await pool.query(`DELETE from events WHERE events.id = $1 RETURNING id`, [id],
(err, results) => {
if (err) {
let msg = err.message;
return res.status(409).send({msg});
} else {
let msg = results;
return res.status(200).send({msg});
}
});
} catch (error) {
return error;
}
});
router.post("/events/occurrenceDelete", async (req, res) => {
try {
let occurrenceId = req.body.id;
await pool.query(`DELETE from events WHERE events.occurrenceId = $1 RETURNING occurrenceId`, [occurrenceId],
(err, results) => {
if (err) {
let msg = err.message;
return res.status(409).send({msg});
} else {
let msg = results;
return res.status(200).send({msg});
}
});
} catch (error) {
return error;
}
});
router.get("/events/recurring", async (req, res) => {
try {
let occurrenceId = req.body.occurrenceId;
const response = await pool.query(`SELECT id, start, end, until, occurrenceId, title, description, category, priority, allDay, done, interval, every, Sun, Mon, Tue, Wed, Thu, Fri, Sat FROM events WHERE events.occurrenceId = occurrenceId RETURNING id`, [occurrenceId],
(err, results) => {
if (err) {
let msg = err.message;
return res.status(500).send({msg});
} else {
let msg = results;
return res.status(200).send({msg});
}
});
} catch (error) {
return error;
}
});
server.get("/api", (req, res) => {
return res.status;
});
router.get("/api/login", checkAuthenticated, (req, res) => {
return res.status;
});
// passport login
router.post("/api/login", passport.authenticate("local"), function (req, res) {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
let msg = {
custid: req.user.custid,
firstname: req.user.firstname,
lastname: req.user.lastname,
email: req.user.email,
cell: req.user.cell,
addr1: req.user.addr1,
addr2: req.user.addr2,
city: req.user.city,
st: req.user.st,
zip: req.user.zip,
usertype: req.user.usertype
};
console.log(`\n\nreq.session.passport.user: `, req.session.passport.user);
return res.status(200).json({ msg });
});
// passport if authenticated return customer object
router.get("/api/isAuthenticated", checkAuthenticated, (req, res) => {
let msg = {
custid: req.user.custid,
firstname: req.user.firstname,
lastname: req.user.lastname,
email: req.user.email,
cell: req.user.cell,
addr1: req.user.addr1,
addr2: req.user.addr2,
city: req.user.city,
st: req.user.st,
zip: req.user.zip,
usertype: req.user.usertype
};
console.log(`\n\nisAuthenticated req.session.passport.user: `, req.session.passport.user);
console.log(`\n\nisAuthenticated msg: `, msg);
return res.status(200).json({ msg });
//return res.status(200).send("Ok");
});
// passport logout
router.get('/api/logout', function (req, res) {
console.log(`\n logout: `, req);
req.logout();
res.status(200).clearCookie('connect.sid', { path: '/' }).json({ status: "Success" });
req.session.destroy(function (err) {
// if (!err)
// {
// res.status(200).clearCookie('connect.sid', { path: '/' }).json({ status: "Success" });
//res.redirect('/');
// } else
// {
// // handle error case...
// console.log(`err: `, err);
// }
});
return;
});
// add new customer
router.post("/api/addcustomer", async (req, res) => {
try
{
let {
firstname,
lastname,
email,
cell,
addr1,
addr2,
city,
st,
zip,
pwd,
usertype,
} = req.body;
let hashedpwd = await bcrypt.hash(pwd, saltRounds);
usertype = "customer";
console.log(`\nPOST addcustomer req.body: `, req.body);
//insert new Customer
pool.query(`INSERT INTO customer (firstname, lastname, email, cell, addr1, addr2, city, st, zip, pwd, usertype)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING custid, firstname, lastname, email, cell, addr1, addr2, city, st, zip, usertype`,
[firstname, lastname, email, cell, addr1, addr2, city, st, zip, hashedpwd, usertype],
(err, result) => {
//Insert failed
if (err)
{
console.error(`\naddcustomer INSERT failed. error: `, err.message);
let msg = err.message;
return res.status(409).send(msg);
}
if (result.rowCount === 0)
{
let msg = "insert failed"
return res.status(406).send(msg);
}
else
{ //Insert succeeded
console.error(`\naddcustomer INSERT success: `, result);
//return res.status(200).json(result.rows[0]);
return res.status(200).send(result.rows[0]);
//return res.status(200).send(result);
}
}
);
return res.status;
} catch (error)
{
return error;
}
});
// change password
router.post("/api/changepassword", async function (req, res) {
console.error(`POST /changepassword req.body: `, req.body);
const {
custid,
pwd,
} = req.body;
let hashedPwd = await bcrypt.hash(pwd, saltRounds);
//update existing Customer with NEW password
console.error(`\nUpdate with new password. req.body: `, req.body);
pool.query(
'UPDATE customer SET pwd = $2 WHERE customer.custid = $1 RETURNING custid, firstname, lastname, email, cell, addr1, addr2, city, st, zip, usertype',
[custid, hashedPwd],
(err, results) => {
//Update failed
if (err)
{
console.error(`\nchangepassword failed. error: `, err.message);
let msg = err.message;
return res.status(409).send({ msg });
//Update succeeded
} else
{
console.error(`\nchangepassword success: `, results);
let msg = results;
return res.status(200).json({ msg });
}
}
);
});
// update customer
router.post("/api/updatecustomer", async function (req, res) {
console.error(`\nPOST /updatecustomer req.body: `, req.body);
const {
custid,
firstname,
lastname,
email,
cell,
addr1,
addr2,
city,
st,
zip,
pwd,
usertype,
} = req.body;
if (pwd)
{
let hashedPwd = await bcrypt.hash(pwd, saltRounds);
//update existing Customer with NEW password
console.error(`\nUpdate with new password. req.body: `, req.body);
pool.query(
'UPDATE customer SET firstname = $2, lastname = $3, email = $4, cell = $5, addr1 = $6, addr2 = $7, city = $8, st = $9, zip = $10, usertype = $11, pwd = $12 WHERE customer.custid = $1 RETURNING custid, firstname, lastname, email, cell, addr1, addr2, city, st, zip, usertype',
[custid, firstname, lastname, email, cell, addr1, addr2, city, st, zip, usertype, hashedPwd],
(err, results) => {
//Update failed
if (err)
{
console.error(`\nupdatecustomer failed. error: `, err.message);
let msg = err.message;
return res.status(409).send({ msg });
//Update succeeded
} else
{
console.error(`\nupdatecustomer success: `, results.rowCount);
let msg = results.rowCount;
return res.status(200).send({ msg });
}
}
);
} else
{
//update customer with existing password
console.error(`\nUpdate with existing password. req.body: `, req.body);
pool.query(
'UPDATE customer SET firstname = $2, lastname = $3, email = $4, cell = $5, addr1 = $6, addr2 = $7, city = $8, st = $9, zip = $10, usertype = $11 WHERE customer.custid = $1 RETURNING custid, firstname, lastname, email, cell, addr1, addr2, city, st, zip, usertype',
[custid, firstname, lastname, email, cell, addr1, addr2, city, st, zip, usertype],
(err, results) => {
//Update failed
if (err)
{
console.error(`\nUpdate failed. error: `, err.message);
let msg = err.message;
return res.status(409).send(msg);
//Update succeeded
} else
{
console.error(`\nUpdate success: `, results.rowCount);
let msg = results.rows[0];
return res.status(200).send(msg);
}
}
);
};
});
// get customer by custid
router.get("/api/getcustomerbycustid/:custid", async (req, res) => {
let custid = req.params.custid;
try
{
const response = await pool.query(
`SELECT custid, firstname, lastname, email, cell, addr1, addr2, city, st, zip, usertype, username, createdate FROM customer WHERE customer.custid = $1`, [custid]);
if (response.rows.length > 0)
{
console.log(`\ngetcustomerbycustid response: `, response);
return res.status(200).json(response.rows[0]);
}
} catch (err)
{
return res.status(404).json(err.message);
}
});
router.get("/api/listcustomers", async (req, res) => {
const response = await pool.query(`SELECT custid, firstname, lastname, email, cell, addr1, addr2, city, st, zip, usertype, createdate, lastupdate FROM customer`);
if (response.rows.length > 0)
{
console.log(`\n\nlistcustomers response.rows: `, response.rows);
return res.status(200).send(response.rows);
}
return res.status(404);
});
// delete customer by custid
router.delete("/api/deletecustomer/:custid", async function (req, res) {
try {
let custid = req.params.custid;
const response = await pool.query(
`DELETE from customer WHERE customer.custid = $1 RETURNING custid`, [custid]);
if (response) {
console.log(`\n\ndeletecustomer response: `, response.rows);
return res.status(200).send(response.rows);
}
} catch (err) {
console.log(`\n\ndelete customer err: `, err);
return res.status(404).send(err);
}
});
// add new subscription for custid and zip
router.post("/api/addsubscription", async (req, res) => {
try
{
const foundSubscription = await pool.query(
`SELECT * from subscriber WHERE subscriber.custid = $1 AND subscriber.zip = $2`, [req.body.custid, req.body.zip]
);
if (foundSubscription.rows.length > 0)
{
return res.status(409).send('error: duplicate subscription found');
} else
{
const {
custid,
cell,
zip,
nickname,
weatheralert,
virusalert,
airalert,
} = req.body;
pool.query(`INSERT INTO subscriber (custid, cell, zip, nickname, weatheralert, virusalert, airalert) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id, custid, cell, zip, nickname, weatheralert, virusalert, airalert`,
[custid, cell, zip, nickname, weatheralert, virusalert, airalert],
(err, results) => {
//Insert failed
if (err)
{
console.error(`\naddsubscription INSERT failed. error: `, err.message);
let msg = err.message;
return res.status(409).send(msg);
//Insert succeeded
} else
{
console.error(`\n\naddsubscription INSERT success: `, results.rows);
return res.status(200).send(results.rows);
}
}
);
//return res;
};
} catch (err)
{
return (err);
}
});
// update existing subscription for custid & zip
router.post("/api/updatesubscription", async (req, res) => {
try
{
const {
custid,
id,
cell,
zip,
nickname,
weatheralert,
virusalert,
airalert,
} = req.body;
const foundSubscription = await pool.query(
`SELECT * from subscriber WHERE subscriber.custid = $1 AND subscriber.id = $2`, [custid, id]);
if (foundSubscription.rows.length > 0)
{
await pool.query(`UPDATE subscriber SET cell = $3, zip = $4, nickname = $5, weatheralert = $6, virusalert = $7, airalert = $8 WHERE subscriber.custid = $1 AND subscriber.id = $2 RETURNING subscriber.id, subscriber.custid, cell, zip, nickname, weatheralert, virusalert, airalert`, [custid, id, cell, zip, nickname, weatheralert, virusalert, airalert],
(err, results) => {
if (results)
{
console.log(`\n\nupdatesubscription success results.rows[0]: `, results.rows[0])
return res.status(200).send(results.rows[0]);
}
return res.status(404).send(err);
}
);
};
return res;
} catch (err)
{
console.log(`\n\nupdatesubscription error: `, err.name, err.message);
return (err)
}
});
// delete subscription by subscriber.id
router.delete("/api/deletesubscription/:id", async function (req, res) {
try
{
let id = req.params.id;
console.log(`\n\ndeletesubscription id: `, id);
const response = await pool.query(`DELETE FROM subscriber WHERE subscriber.id = $1 RETURNING id, custid, zip`, [id]);
if (response)
{
console.log(`\n\ndeletesubscription response: `, response.rows);
return res.status(200).send(response.rows);
}
//console.log(`\n\ndeletesubscription response: `, response.rows);
//return res.status(404).send(response.rows);
} catch (err)
{
console.log(`\n\ndelete subscription err: `, err);
return res.status(404).send(err);
}
});
// getLocationsByCustid
router.get("/api/getlocationsbycustid/:custid", async (req, res) => {
let custid = req.params.custid;
try
{
const response = await pool.query(`SELECT subscriber.id, subscriber.zip, cell, custid, nickname, weatheralert, virusalert, airalert, stateid, city FROM subscriber INNER JOIN zipdata ON zipdata.zip = subscriber.zip WHERE subscriber.custid = $1`, [custid]);
if (response.rowCount > 0)
{
console.log(`\n\ngetlocationsbycustid response: `, response.rows);
return res.status(200).send(response.rows);
}
console.log(`\n\ngetlocationsbycustid 404 response: `, response);
return res.status(404).send(response.rows);
//return res.status(404).send(`locations not found for custid ${custid}`);
} catch (err)
{
console.log(`\n\nerr: `, err);
return res.status(404).send(err.message);
}
});
// getLocationById
router.get("/api/getlocationbyid/:id", async (req, res) => {
let id = req.params.id;
try
{
const response = await pool.query(`SELECT subscriber.id, subscriber.zip, cell, custid, nickname, weatheralert, virusalert, airalert, stateid, city FROM subscriber INNER JOIN zipdata ON zipdata.zip = subscriber.zip WHERE subscriber.id = $1`, [id]);
if (response.rowCount > 0)
{
console.log(`\n\ngetlocationbyid response: `, response.rows);
return res.status(200).send(response.rows[0]);
}
console.log(`\n\ngetlocationbyid 404 response: `, response);
return res.status(404).send(response.rows);
//return res.status(404).send(`locations not found for custid ${custid}`);
} catch (err)
{
console.log(`\n\nerr: `, err);
return res.status(404).send(err.message);
}
});
// list subscriptions for custid
router.post("/api/listsubscriptions", async (req, res) => {
try
{
const {
custid
} = req.body;
const response = await pool.query(`SELECT subscriber.id, subscriber.zip, cell, custid, nickname, weatheralert, virusalert, airalert, stateid, city FROM subscriber INNER JOIN zipdata ON zipdata.zip = subscriber.zip WHERE subscriber.custid = $1`, [custid]);
if (response.rowCount > 0)
{
console.log(`\n\nresponse: `, response);
return res.status(200).json(response.rows);
}
console.log(`\n\nrowCount = 0 response: `, response);
return res.status(404).json(`No subscriptions found for custid ${custid}`);
} catch (err)
{
console.log(`\n\nerr: `, err);
return (err);
}
});
// add new friend for custid
router.post("/api/addfriend", async (req, res) => {
try
{
const foundFriend = await pool.query(
`SELECT * from friends WHERE friends.custid = $1 AND friends.cell = $2`, [req.body.custid, req.body.cell]);
if (foundFriend.rows.length > 0)
{
return res.status(418).send('error: friend with duplicate cell found');
} else
{
const {
custid,
firstname,
zip,
cell,
} = req.body;
pool.query(`INSERT INTO friends (custid, firstname, zip, cell) VALUES ($1, $2, $3, $4) RETURNING id, custid, zip, firstname, cell`,
[custid, firstname, zip, cell],
(err, results) => {
//Insert failed
if (err)
{
console.error(`\nFriend INSERT failed. error: `, err.message);
let msg = err.message;
return res.status(409).send({ msg });
//Insert succeeded
} else
{
console.error(`\n\nFriend INSERT success: `, results.rows);
return res.status(200).send(results.rows);
}
}
);
//return res;
};
} catch (err)
{
return (err);
};
});
// update existing friend for custid & id
router.post("/api/updatefriend", async function (req, res) {
try
{
const {
custid,
firstname,
zip,
cell,
id,
} = req.body;
const foundFriend = await pool.query(`SELECT * from friend WHERE friend.custid = $1 and friend.id = $2`, [custid, id]);
if (foundFriend.rows.length > 0)
{
await pool.query(`UPDATE friends SET firstname = $2, zip = $3, cell = $4 WHERE friends.custid = $1 AND friends.id = $5 RETURNING *`,
[custid, firstname, zip, cell, id],
(err, results) => {
if (results)
{
console.log(`\n\nupdatefriend success results.rows[0]: `, results.rows[0])
return res.status(200).send(results.rows[0]);
}
return res.status(404).send(err);
}
);
};
return res;
} catch (err)
{
console.log(`\n\nupdatefriend error: `, err.name, err.message);
return (err)
}
});
// delete friend
router.delete("/api/deletefriend/:id", async function (req, res) {
try
{
let id = req.params.id;
const response = await pool.query(
`DELETE from friends WHERE friends.id = $1 RETURNING *`, [id]);
if (response)
{
console.log(`\n\ndeletefriend response: `, response.rows);
return res.status(200).send(response.rows);
}
} catch (err)
{
console.log(`\n\ndelete friend err: `, err);
return res.status(404).send(err);
}
});
//getfriendsbycustid
router.get("/api/getfriendsbycustid/:custid", async (req, res) => {
let custid = req.params.custid;
try
{
const response = await pool.query(`SELECT friends.id, friends.zip, cell, custid, firstname, stateid, city FROM friends INNER JOIN zipdata ON zipdata.zip = friends.zip WHERE friends.custid = ${custid}`);
if (response)
{
console.log(`\n\ngetfriendsbycustid response: `, response);
return res.status(200).send(response);
}
console.log(`\n\ngetfriendsbycustid 404 response: `, response);
return res.status(404).send(response);
//return res.status(404).send(`friends not found for custid ${custid}`);
} catch (err)
{
console.log(`\n\nerr: `, err);
return res.status(404).send(err.message);
}
});
// get list of friends for custid
router.post("/api/listfriends", async function (req, res) {
let {
custid
} = req.body;
const friendcount = await pool.query(`SELECT COUNT(*) as num FROM friends WHERE friends.custid = $1`, [custid]);
console.log(`friendcount: `, friendcount);
if (friendcount.rows[0].num === '0')
{
return res.status(204).json('No friends found');
}
let list;
if (friendcount.rows[0].num > 0)
{
list = await pool.query(`SELECT * from friends WHERE friends.custid = $1`, [custid]);
return res.status(200).json({ list });
}
return res.status(200).json({ list });
});
// verify zip
router.post("/api/verifyzip", async (req, res) => {
try
{
const {
zip,
} = req.body;
const foundZip = await pool.query(`SELECT zipdata.zip FROM zipdata WHERE zipdata.zip = $1`, [zip]
);
if (foundZip.rows.length > 0)
{
return res.status(200).send(foundZip.rows[0]);
}
return res.status(404).json({ msg: `zip code ${req.body.zip} not found` });
} catch (err)
{
return (err);
}
});
// POST get zip with highest pop for city/st
router.post("/api/findzip", async (req, res) => {
try
{
const {
city,
st,
} = req.body;
const foundZip = await pool.query(`SELECT zipdata.zip FROM zipdata WHERE zipdata.city = $1 AND zipdata.stateid = $2 ORDER BY zipdata.pop DESC LIMIT 1`, [city, st]
);
if (foundZip.rows.length > 0)
{
console.log(`\nZip found `, foundZip.rows[0].zip, req.body.city, req.body.st);
return res.status(200).json(foundZip.rows[0].zip);
}
return res.status(404).json({ msg: `Zip not found for ${req.body.city}, ${req.body.st}` });
} catch (err)
{
console.log(`\n\nerr: `, err);
return (err);
}
});
// get zip with highest pop for city/st
router.get("/api/getzip", async (req, res) => {
try
{
let city = req.params.city;
let stateid = req.params.st;
const foundZip = await pool.query(`SELECT zipdata.zip FROM zipdata WHERE zipdata.city = $1 AND zipdata.stateid = $2 ORDER BY zipdata.pop DESC LIMIT 1`, [city, stateid]);
console.log(`\n\nZip found `, foundZip.rows[0], city, stateid);
return res.status(200).json(foundZip.rows[0]);
} catch (err)
{
console.log(`\n\nerr: `, err);
return (err);
}
});
// get city/st for zip
router.get("/api/getcityst/:zip", async (req, res) => {
let zip = req.params.zip;
try
{
const response = await pool.query(`SELECT zipdata.city, zipdata.stateid FROM zipdata WHERE zipdata.zip = $1`, [zip]);
return res.status(200).json(response.rows[0]);
} catch (err)
{
return res.status(err.status).json(err.message);
}
});
// check for duplicate customer email
router.get("/api/checkemail", async (req, res) => {
let custid = req.params.custid;
let email = req.params.email;
try
{
const foundEmail = await pool.query(`SELECT customer.custid, customer.email FROM customer WHERE customer.email = $1 AND customer.custid != $2`, [email, custid]);
if (foundEmail.rows.length > 0)
{
return res.status(418).json(`Duplicate email found. `, foundEmail.rows[0]);
}
return res.status(200).json(`Email ${email} for custid ${custid} not a duplicate `);
} catch (err)
{
return (err);
}
});
//check for duplicate customer cell
router.get("/api/checkcell", async (req, res) => {
let custid = req.params.custid;
let cell = req.params.cell;
try
{
const foundCell = await pool.query(`SELECT customer.custid, customer.cell FROM customer WHERE customer.cell = $1 AND customer.custid != $2`, [cell, custid]);
return res.status(200).json(`Cell ${cell} for custid ${custid} not a duplicate `)
} catch (err)
{
return res.status().json(err.name, err.message);
}
});
// check for duplicate email in customer table
router.post("/api/checkemail", async (req, res) => {
try
{
const {
email,
custid
} = req.body;