-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresolvers.js
executable file
·63 lines (59 loc) · 1.92 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
const { AuthenticationError, PubSub } = require('apollo-server');
const Pin = require('./models/Pin');
const pubsub = new PubSub();
const PIN_ADDED = "PIN_ADDED";
const PIN_UPDATED = "PIN_UPDATED";
const PIN_DELETED = "PIN_DELETED";
const CREATE_COMMENT = "CREATE_COMMENT";
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) => 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();
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)
},
pinUpdated: {
subscribe: () => pubsub.asyncIterator(PIN_UPDATED)
},
pinDeleted: {
subscribe: () => pubsub.asyncIterator(PIN_DELETED)
}
}
};