Skip to content

Instantly share code, notes, and snippets.

@dohomi
Last active June 19, 2018 00:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dohomi/cecd58454512d682c83d814e1b56cfbb to your computer and use it in GitHub Desktop.
Save dohomi/cecd58454512d682c83d814e1b56cfbb to your computer and use it in GitHub Desktop.
graphql-yoga and CRUD example with subscription
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)
}
},
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