forked from sadatakhtar/QuestionMark-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
689 lines (582 loc) · 22.9 KB
/
server.js
File metadata and controls
689 lines (582 loc) · 22.9 KB
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
const express = require ('express');
const app = express ();
const cors = require ('cors');
const Pool = require ('pg').Pool;
const nodemailer = require ('nodemailer');
require ('dotenv').config ();
// setting time zone
process.env.TZ = 'Europe/London';
// we use process.env to contain our environment variables
//(variable to describe the enviroment our app is going to run in)
//because Herohu is responsible for the environment
//Heroku will provide some variables to apply for our app one of them is PORT .
const PORT = process.env.PORT || 5000;
const devConfig = {
user: process.env.PG_USER,
password: process.env.PG_PASSWORD,
host: process.env.PG_HOST,
port: process.env.PG_PORT,
database: process.env.PG_DATABASE,
};
const proConfig = {
connectionString: process.env.DATABASE_URL, //coming from Heroku addons
};
const pool = new Pool (
process.env.NODE_ENV === 'production' ? proConfig : devConfig
);
// middleware
app.use (cors ());
app.use (express.json ()); //allow use to access request.body
app.use (express.urlencoded ({extended: true}));
app.use (function (req, res, next) {
res.header ('Access-Control-Allow-Origin', '*');
res.header (
'Access-Control-Allow-Headers',
'Origin,X-Requested-With,Content-Type,Accept'
);
next ();
});
// answers is the answers counter
// rate is the likes counter
//****************************************** ROUTES ****************************************************************
app.get ('/', (req, res) => {
res.sendFile (__dirname + '/index.html');
});
app.post ('/validEmail', async (req, res) => {
const {email, password} = req.body;
const router = express.Router ();
const emailValidator = require ('deep-email-validator');
if (!email || !password) {
return res.status (400).send ({
message: 'Email or password missing.',
});
}
async function isEmailValid (email) {
return emailValidator.validate (email);
}
const {valid, reason, validators} = await isEmailValid (email);
if (valid) return res.send ({message: 'OK'});
return res.status (400).send ({
message: 'Please provide a valid email address.',
reason: validators[reason].reason,
});
});
//****************************************************************************************************************************************** */
//*********************************************** Get all questions *************************************************
app.get ('/allquestions', async (req, res) => {
try {
const allquestions = await pool.query (
`select id, module_id,question_title, question,answers,to_char(question_date,'DD-MM-YYYY') as question_date,views,rate from question`
);
const count = await pool.query ('select count(question) from question');
const filter = await pool.query ('select id,module from module');
const q_answers = await pool.query (
'select question.question,answer.answer from question inner join answer on question.id = answer.question_id'
);
const data = {};
data.allquestions = allquestions.rows;
data.count = count.rows[0];
data.filter = filter.rows;
data.q_answers = q_answers.rows;
res.json (data);
} catch (err) {
console.error (err.message);
}
});
//****************************************************************************************************************************************** */
//*********************************************** Get all answered questions *************************************************
app.get ('/answered', async (req, res) => {
try {
const answered = await pool.query (
`select answer.question_id,question.question, to_char(question.question_date,'DD-MM-YYYY') as question_date, question.answers,question.module_id,answer.answer, to_char(answer.answer_date,'DD-MM-YYYY') as answer_date from question inner join answer on question.id = answer.question_id`
);
const filter = await pool.query ('select id,module from module');
const data = {};
data.answered = answered.rows;
data.filter = filter.rows;
res.json (data);
} catch (err) {
console.error (err.message);
}
});
//****************************************************************************************************************************************** */
//***************************************** Get all unanswered questions **************************************************
app.get ('/unanswered', async (req, res) => {
try {
const unanswered = await pool.query (
`select question.id,question.question,question.module_id,to_char(question.question_date, 'DD-MM-YYYY') as question_date ,users.name from question inner join users on users.id = question.users_id where question.answers= 0`
);
const filter = await pool.query ('select id,module from module');
const data = {};
data.unanswered = unanswered.rows;
data.filter = filter.rows;
res.json (data);
} catch (err) {
console.error (err.message);
}
});
//****************************************************************************************************************************************** */
//***************************************** Get selected question description *********************************************
app.get ('/selectedquestionpage/:id', async (req, res) => {
const id = req.params.id;
const data = {};
try {
const selectedquestion = await pool.query (
`select question.id, question.question_title,question.module_id, question.question,to_char (question.question_date, 'DD-MM-YYYY') as question_date,question.answers,question.rate,question.views,users.name,users.email from question inner join users on users.id = question.users_id where question.id =$1 `,
[id]
);
const selectedquestion_answer = await pool.query (
`select answer.id,answer.question_id,answer.answer,answer.users_id,users.name,to_char(answer.answer_date, 'DD-MM-YYYY') as answer_date from answer inner join users on users.id = answer.users_id where answer.question_id = $1`,
[id]
);
data.question = selectedquestion.rows;
data.answer = selectedquestion_answer.rows;
res.json (data);
} catch (err) {
console.error (err.message);
}
});
//****************************************************************************************************************************************** */
app.post ('/sendmail', async (req, res) => {
let incomingEmail = req.body.email;
let ask_question_email;
let incomingText = req.body.text;
if (req.body.users_id) {
let userEmailQuery = await pool.query (
'select email from users where id =$1',
[req.body.users_id]
);
ask_question_email = userEmailQuery.rows[0].email;
}
if (incomingEmail === 'false') {
incomingEmail = ask_question_email;
}
if (req.body.send === true) {
const transporter = nodemailer.createTransport ({
service: 'gmail',
auth: {
user: 'questionmarkcyf@gmail.com',
pass: process.env.EMAIL_PASS,
},
});
const mailOptions = {
from: 'questionmarkcyf@gmail.com',
to: incomingEmail,
subject: 'Q&A Notification',
text: `${incomingText}`,
};
transporter.sendMail (mailOptions, (error, info) => {
if (error) {
console.log (error);
} else {
console.log (`Email Sent: ${info.response}`);
}
});
res.send ('Email sent');
} else {
res.send ('Email sending failed!');
}
});
//****************************************************************************************************************************************** */
//******************************************* Post a reply to question by id *******************************
app.post ('/replypage', async (req, res) => {
console.log (req.body);
const question_id = req.body.question_id;
const user_id = req.body.user_id;
const date = req.body.date;
const reply = req.body.reply;
try {
const replyDescription = await pool.query (
'INSERT INTO answer(question_id,answer,users_id,answer_date) VALUES($1,$2,$3,$4) RETURNING *',
[question_id, reply, user_id, date]
);
const increaseAnswers = await pool.query (
'UPDATE question SET answers = answers+1 WHERE id = $1',
[question_id]
);
res.json (replyDescription.rows[0]).status (200);
} catch (err) {
console.error (err.message);
}
});
//****************************************************************************************************************************************** */
//******************************************* endpoint for getting the views and likes counters *******************************
app.get ('/counters', async (req, res) => {
try {
const conterData = await pool.query ('select id,views,rate from question');
res.json (conterData.rows);
} catch (err) {
console.error (err.message);
}
});
//****************************************************************************************************************************************** */
//*************************************** endpoint to update the likes ********************************************
app.put ('/rates', async (req, res) => {
const id = req.body.id;
const rate = req.body.rate;
try {
const rates = await pool.query ('UPDATE question SET rate=$1 WHERE id=$2', [
rate,
id,
]);
res.json (rates.rows);
} catch (err) {
console.error (err.message);
}
});
//****************************************************************************************************************************************** */
//**************************************** endpoint to update the views *********************************************
app.put ('/views', async (req, res) => {
const id = req.body.id;
const views = req.body.views;
try {
const viewsRes = await pool.query (
'UPDATE question SET views=$1 WHERE id=$2',
[views, id]
);
res.json (viewsRes.rows);
} catch (err) {
console.error (err.message);
}
});
//****************************************************************************************************************************************** */
//***************************************** Endpoint for getting a user answers *****************************************
app.get ('/userAnswers/:id', async (req, res) => {
const id = parseInt (req.params.id);
try {
const answers = await pool.query (
'select answer.id,question.question,answer.answer,answer.question_id,question.module_id from question inner join answer on question.id = answer.question_id where answer.users_id = $1',
[id]
);
res.json (answers.rows);
} catch (err) {
console.error (err.message);
}
});
//****************************************************************************************************************************************** */
//**************************************** Endpoint for getting asked questions by a user **********************************
app.get ('/userAsked/:id', async (req, res) => {
const id = parseInt (req.params.id);
try {
const userAskedQ = await pool.query (
'select question.id,question.question,question.answers from question where question.users_id = $1 ',
[id]
);
// const AnswersForuserAskedQ = await pool.query (
// 'select question.answers where question.users_id = $1 ',
// [id]
// );
res.json (userAskedQ.rows);
} catch (err) {
console.error (err.message);
}
});
//test
app.get ('/test', async (req, res) => {
const answer_question_id = await pool.query (
'select question_id from answer where id = 1'
);
res.json (answer_question_id.rows[0].question_id);
});
//****************************************************************************************************************************************** */
//******************************************* Endpoint to delete a user's answer by id ***********************************
app.delete ('/userAnswers/:id', async (req, res) => {
try {
const id = req.params.id;
const answer_question_id = await pool.query (
'select question_id from answer where id = $1',
[id]
);
const decreaseAnswers = await pool.query (
'UPDATE question SET answers = answers-1 WHERE id = $1',
[answer_question_id.rows[0].question_id]
);
const deleteAnswer = await pool.query ('delete from answer where id = $1', [
id,
]);
res.json ('Answer was deleted');
} catch (err) {
console.error (err.message);
}
});
//****************************************************************************************************************************************** */
//***************************************** Endpoint delete a user's question by id *********************************
app.delete ('/userAsked/:id', async (req, res) => {
try {
const id = req.params.id;
const deleteAllAnswers = await pool.query (
'delete from answer where question_id = $1',
[id]
);
const deleteQuestion = await pool.query (
'delete from question where id = $1',
[id]
);
const deleteAnswers = await pool.query (
'delete from answer where question_id = $1',
[id]
);
res.json ('Question was deleted');
} catch (err) {
console.error (err.message);
}
});
//****************************************************************************************************************************************** */
//***************************************** Endoint to edit a user's answer *********************************************
app.put ('/userAnswers/:id', async (req, res) => {
console.log ('body = ' + req.body + 'params-id = ' + req.params.id);
try {
const id = req.params.id;
const answer = req.body.answer;
const updateAnswer = await pool.query (
'update answer set answer = $1 where id = $2',
[answer, id]
);
res.json ('Answer updated');
} catch (err) {
console.error (err.message);
}
});
//****************************************************************************************************************************************** */
//*************************************** Endoint to edit user's question *********************************************
app.put ('/userAsked/:id', async (req, res) => {
console.log ('body = ' + req.body.question + 'params-id = ' + req.params.id);
try {
const id = req.params.id;
const question = req.body.question;
const updateQuestion = await pool.query (
'update question set question = $1 where id = $2',
[question, id]
);
res.json ('Question updated');
} catch (err) {
console.error (err.message);
}
});
//****************************************************************************************************************************************** */
//*************************************** Endoint to Add a comment to an answer *********************************************
app.post ('/comments', async (req, res) => {
console.log (req.body);
const comment = req.body.comment;
const question_id = req.body.question_id;
const answer_id = req.body.answer_id;
const users_id = req.body.users_id;
const date = req.body.date;
try {
const commentDescription = await pool.query (
'INSERT INTO comment(comment,question_id,answer_id,users_id,comment_date) VALUES($1,$2,$3,$4,$5) RETURNING *',
[comment, question_id, answer_id, users_id, date]
);
const increaseComments = await pool.query (
'UPDATE comment SET comments_counter = comments_counter+1 WHERE answer_id = $1',
[answer_id]
);
res.json (commentDescription.rows[0]).status (200);
} catch (err) {
console.error (err.message);
}
});
//******************************************************************************************************************************************
//*************************************** Endoint to get all the comments *********************************************
app.get ('/comments', async (req, res) => {
try {
const displayComment = await pool.query (
'select *from comment ORDER BY comment_date DESC'
);
res.json (displayComment.rows).status (200);
} catch (err) {
console.error (err.message);
}
});
//******************************************************************************************************************************************
//*************************************** Endoint to get all the likes details *********************************************
app.get ('/likes', async (req, res) => {
try {
const displayLikes = await pool.query ('select *from likes');
res.json (displayLikes.rows).status (200);
} catch (err) {
console.error (err.message);
}
});
//******************************************************************************************************************************************
//*************************************** Endoint to get likes of a question for a user *********************************************
app.get ('/likes/:user_id/:question_id', async (req, res) => {
try {
const user_id = req.params.user_id;
const question_id = req.params.question_id;
const displayLikes = await pool.query (
'select likes from likes where users_id=$1 and question_id = $2',
[user_id, question_id]
);
res.json (displayLikes.rows[0].likes).status (200);
} catch (err) {
console.error (err.message);
}
});
//******************************************************************************************************************************************
//*************************************** Endoint to update likes for a user *********************************************
app.put ('/likes/:user_id/:question_id', async (req, res) => {
try {
const user_id = req.params.user_id;
const question_id = req.params.question_id;
const updateLikes = pool.query (
'update likes set likes = NOT likes where users_id =$1 and question_id=$2'[
(user_id, question_id)
]
);
res.json (updateLikes.rows).status (200);
} catch (err) {
console.error (err.message);
}
});
//******************************************************************************************************************************************
app.post ('/sendmail', async (req, res) => {
let incomingEmail = req.body.email;
let ask_question_email;
let incomingText = req.body.text;
if (req.body.users_id) {
let userEmailQuery = await pool.query (
'select email from users where id =$1',
[req.body.users_id]
);
ask_question_email = userEmailQuery.rows[0].email;
}
if (incomingEmail === 'false') {
incomingEmail = ask_question_email;
}
if (req.body.send === true) {
const transporter = nodemailer.createTransport ({
service: 'gmail',
auth: {
user: 'questionmarkcyf@gmail.com',
pass: process.env.EMAIL_PASS,
},
});
const mailOptions = {
from: 'questionmarkcyf@gmail.com',
to: incomingEmail,
subject: 'Testing nodemailer',
text: `${incomingText}`,
};
transporter.sendMail (mailOptions, (error, info) => {
if (error) {
console.log (error);
} else {
console.log (`Email Sent: ${info.response}`);
}
});
res.send ('Email sent');
} else {
res.send ('Email sending failed!');
}
});
//SIGNUP
app.post ('/register', (req, res) => {
const {username, email, password, confirm} = req.body;
let errorArray = [];
!username ||
!email ||
!password ||
(!confirm && errorArray.push ({message: 'Please enter all fields'}));
password.length < 5 &&
errorArray.push ({message: 'Password should be at least 5 characters'});
password !== confirm && errorArray.push ({message: 'Passwords do not match'});
if (errorArray.length > 0) {
res.send ({errorArray});
} else {
// let hashedPassword = await bcrypt.hash (password, 10);
// console.log(hashedPassword);
pool.query (
`insert into users (name, email, password) values ($1, $2, $3)`,
[username, email, password],
(error, result) => {
console.log (error, result);
if (error) {
res
.status (400)
.send ({error: 'Database connection not established!'});
}
if (result) {
res.status (200).send ({
success: true,
message: ' Registration successfull. Please login',
});
} else {
res.status (401).send ({success: false});
}
}
);
}
});
//LOGIN
app.post ('/login', (req, res) => {
const {username, password} = req.body;
pool.query (
`select * from users where name=$1 and password=$2`,
[username, password],
(error, result) => {
if (error) {
res.status (400).send ({error: 'Database not established!'});
}
if (result.rows.length > 0) {
res.send ({
success: true,
message: `${username}`,
user_id: `${result.rows[0].id}`,
});
} else {
// res.status(401).send({message: "Wrong username/password combination"});
res.status (401).json ({
success: false,
message: 'Invalid username/password. Please register or try again',
});
}
}
);
});
// this End point returns name, answered and unanswered questions for a particular user from their id.
app.get ('/ask-question/:user_id', async (req, res) => {
let user_id = req.params.user_id;
let userObj = {};
const name = await pool.query (' select name from users where id=$1', [
user_id,
]);
userObj.name = name.rows;
const answeredQuestions = await pool.query (
'select id,question_title from question where answers >0 and users_id=$1',
[user_id]
);
userObj.answeredQuestions = answeredQuestions.rows;
const unAnsweredQuestions = await pool.query (
'select id,question_title from question where answers =0 and users_id=$1',
[user_id]
);
userObj.unAnsweredQuestions = unAnsweredQuestions.rows;
res.json (userObj);
});
app.get ('/modules', async (req, res) => {
let moduleQuery = await pool.query ('select module from module');
let modules = moduleQuery.rows;
if (typeof modules != undefined) res.json (modules);
else res.send ('Not working');
});
app.post ('/ask-question', async (req, res) => {
const quesObj = req.body;
// console.log(quesObj);
let askQuestionQuery = await pool.query (
'insert into question(question_title,question,module_id,users_id,question_date,answers) values($1,$2,$3,$4,$5,$6)',
[
quesObj.title,
quesObj.question,
quesObj.module_id,
quesObj.users_id,
quesObj.question_date,
quesObj.answers,
]
);
res.json (true);
});
//SERVER LISTEN
app.listen (PORT, () => {
console.log (`Server Listening on port ${PORT}`);
});