-
Notifications
You must be signed in to change notification settings - Fork 0
/
resolvers.js
70 lines (67 loc) · 2.13 KB
/
resolvers.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 { AuthenticationError, PubSub } = require("apollo-server");
const Pin = require("./models/Pin");
const pubsub = new PubSub();
const PIN_ADDED = "PIN_ADDED";
const PIN_DELETED = "PIN_DELETED";
const PIN_UPDATED = "PIN_UPDATED";
// This is a wrapper function.
// We do this in order to get the current authenticated user: currentUser
const authenticated = next => (root, args, ctx, info) => {
if (!ctx.currentUser) {
throw new AuthenticationError("You must be logged in");
}
return next(root, args, ctx, info);
};
module.exports = {
Query: {
me: authenticated((root, args, ctx, info) => ctx.currentUser),
getPins: async (root, args, ctx) => {
const pins = await Pin.find({})
.populate("author")
.populate("comments.author");
return pins;
}
},
Mutation: {
createPin: authenticated(async (root, args, ctx) => {
const newPin = await new Pin({
...args.input,
author: ctx.currentUser._id
}).save();
const pinAdded = await Pin.populate(newPin, "author");
pubsub.publish(PIN_ADDED, { pinAdded });
return pinAdded;
}),
deletePin: authenticated(async (root, args, ctx) => {
const pinDeleted = await Pin.findOneAndDelete({
_id: args.pinId
}).exec();
console.log({ pinDeleted });
pubsub.publish(PIN_DELETED, { pinDeleted });
return pinDeleted;
}),
createComment: authenticated(async (root, args, ctx) => {
const newComment = { text: args.text, author: ctx.currentUser._id };
const pinUpdated = await Pin.findOneAndUpdate(
{ _id: args.pinId },
{ $push: { comments: newComment } },
{ new: true }
)
.populate("author")
.populate("comments.author");
pubsub.publish(PIN_UPDATED, { pinUpdated });
return pinUpdated;
})
},
Subscription: {
pinAdded: {
subscribe: () => pubsub.asyncIterator(PIN_ADDED)
},
pinDeleted: {
subscribe: () => pubsub.asyncIterator(PIN_DELETED)
},
pinUpdated: {
subscribe: () => pubsub.asyncIterator(PIN_UPDATED)
}
}
};