-
Notifications
You must be signed in to change notification settings - Fork 0
/
resolvers.js
executable file
·64 lines (61 loc) · 2.12 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
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"
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)
},
pinDeleted: {
subscribe: () => pubSub.asyncIterator(PIN_DELETED)
},
pinUpdated: {
subscribe: () => pubSub.asyncIterator(PIN_UPDATED)
}
}
}