-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCommentController.js
70 lines (52 loc) · 2.18 KB
/
CommentController.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
const { CommentService } = require('../services')
const { errorWrapper, errorGenerator } = require('../errors')
const getComments = errorWrapper(async (req, res) => {
const { articleId } = req.params
const comments = await CommentService.fetchComments({ article_id: Number(articleId) })
res.status(200).json({ comments })
})
const postComment = errorWrapper(async (req, res) => {
const { articleId } = req.params
const { id: userIdFromToken } = req.foundUser
const { body } = req.body
const createdComment = await CommentService.createComment({
article_id: Number(articleId),
user_id: userIdFromToken,
body,
})
res.status(201).json({ createdComment })
})
const updateComment = errorWrapper(async (req, res) => {
const { articleId, commentId } = req.params
const { body } = req.body
const { id: userIdFromToken } = req.foundUser
const comments = await CommentService.fetchComments({ article_id: Number(articleId) })
const foundComment = comments.find((comment) => comment.id === Number(commentId))
if (!foundComment) errorGenerator({ message: 'not found', statusCode: 404 })
const isValidUser = foundComment.user_id === userIdFromToken // true or false
if (!isValidUser) errorGenerator({ message: 'unauthorized', statusCode: 403 })
const updatedComment = await CommentService.updateComment({
comment_id: Number(commentId),
body,
})
res.status(200).json({ updatedComment })
})
const deleteComment = errorWrapper(async (req, res) => {
const { articleId, commentId } = req.params
const { id: userIdFromToken } = req.foundUser
const comments = await CommentService.fetchComments({ article_id: Number(articleId) })
const foundComment = comments.find((comment) => comment.id === Number(commentId))
if (!foundComment) errorGenerator({ message: 'not found', statusCode: 404 })
const isValidUser = foundComment.user_id === userIdFromToken
if (!isValidUser) errorGenerator({ message: 'unauthorized', statusCode: 403 })
const deletedComment = await CommentService.deleteComment({
comment_id: Number(commentId),
})
res.status(200).json({ deletedComment })
})
module.exports = {
getComments,
postComment,
updateComment,
deleteComment,
}