comments.js
1.38 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
const Post = require("../../models/Post");
const checkAuth = require("../../util/check-auth");
const { AuthenticationError, UserInputError } = require("apollo-server");
module.exports = {
Mutation: {
createComment: async (_, { postId, body }, context) => {
const { username } = checkAuth(context);
if (body.trim() === "") {
throw new UserInputError("Empty comment", {
errors: {
body: "Comment body must not empty"
}
});
}
const post = await Post.findById(postId);
if (post) {
post.comments.unshift({
body,
username,
createdAt: new Date().toISOString()
});
await post.save();
return post;
} else throw new UserInputError("Post not found");
},
deleteComment: async (_, { postId, commentId }, context) => {
const { username } = checkAuth(context);
const post = await Post.findById(postId);
if (post) {
const commentIndex = post.comments.findIndex(c => c.id === commentId);
if (post.comments[commentIndex].username === username) {
post.comments.splice(commentIndex, 1);
await post.save();
return post;
} else {
throw new AuthenticationError("Action not allowed");
}
} else {
throw new UserInputError("Post not found");
}
}
}
};