-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathquestions.js
85 lines (75 loc) · 1.84 KB
/
questions.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
const model = require("../model/question-model");
//returns all questions from db
function getAllQuestions(req, res, next) {
model
.getAllQuestions()
.then((questions) => {
res.status(200).send(questions);
})
.catch(next);
}
//returns question associated to question id.
function getQuestion(req, res, next) {
const id = req.params.id;
if (id) {
model
.getQuestionByQuestionId(id)
.then((question) => {
res.status(200).send(question)
})
.catch(next);
}
}
function postNewQuestion(req, res, next) {
const userId = req.user.id
model
.post(req.body, userId)
.then((question) => {
res.status(201).send(question);
})
.catch(next);
}
function updateQuestion(req, res, next) {
const questionId = req.params.id;
const question = req.body.question;
const userId = req.user.id;
//refactor this to get rid of the first model query if possible
model
.getUserIdByQuestionId(questionId)
.then(userIdArr => {
console.log(userIdArr)
if(userIdArr[0].user_id !== userId){
const error = new Error('Unauthorized!')
error.status = 401;
next(error)
} else {
model
.put(questionId, question)
.then((updated) => {
res.status(200).send(updated);
})
.catch(next);
}
})
}
function deleteQuestion(req, res, next){
const questionId = req.params.id;
const userId = req.user.id;
model
.getUserIdByQuestionId(questionId)
.then(userIdArr => {
if(userIdArr[0].user_id !== userId){
const error = new Error('Unauthorized!')
error.status = 401;
next(error)
} else {
model
.del(questionId)
.then(() => {
res.status(204).send();
})
.catch(next);
}
})
}
module.exports = { getAllQuestions, getQuestion, postNewQuestion, updateQuestion, deleteQuestion }