Last active
June 19, 2018 00:07
-
-
Save dohomi/cecd58454512d682c83d814e1b56cfbb to your computer and use it in GitHub Desktop.
graphql-yoga and CRUD example with subscription
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Subscription: { | |
user: { | |
subscribe: (parent, args, {pubSub}) => { | |
return pubSub.asyncIterator([MutationTypes.created, MutationTypes.updated]) | |
} | |
} | |
} | |
Mutation: { | |
updateUser: async (parent, {_id, email, firstName, lastName}, {collections, ObjectID, pubSub}) => { | |
const form = getUserObj({email, firstName, lastName}) | |
try { | |
delete form._id // need to remove the _id modifier | |
const res = await collections.users.updateOne( | |
{_id: ObjectID(_id)}, | |
{$set: form} | |
) | |
if (res.matchedCount !== 1) { | |
throw new Error('error.user_not_found') | |
} | |
const user = await collections.users.findOne({_id: ObjectID(_id)}) | |
Object.assign(user, { | |
_id: _id | |
}) | |
pubSub.publish(MutationTypes.updated, { | |
user:{ | |
mutationType: MutationTypes.updated, | |
node: user | |
} | |
}) | |
return res | |
} catch (e) { | |
console.log(e) | |
throw new Error(e.message) | |
} | |
}, |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type SubscriptionPayload{ | |
mutationType:String | |
node:User | |
} | |
type Subscription{ | |
user:SubscriptionPayload! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment