Skip to content

Commit

Permalink
Subscription - Expanding the Posts Subscription for Edits/Updates. Cl…
Browse files Browse the repository at this point in the history
…oses #14
  • Loading branch information
KazChe committed Sep 22, 2020
1 parent 9651992 commit bf20256
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 6 deletions.
55 changes: 51 additions & 4 deletions src/resolvers/Mutation.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,21 @@ const Mutation = {
...args.data
}

db.posts.push(post);
pubsub.publish('post', {post})
db.posts.push(post)
// publish event only if post.published is tchroo
if(args.data.published) {
pubsub.publish('post',
{
post: {
mutation: 'CREATED',
data: post
}
})
}

return post;
},
deletePost(parent, args, { db }, info) {
deletePost(parent, args, { db, pubsub }, info) {
const postIndex = db.posts.findIndex((post) => post.id === args.id)

if (postIndex === -1) {
Expand All @@ -97,11 +106,21 @@ const Mutation = {

db.comments = db.comments.filter((comment) => comment.post !== args.id)

if(deletedPosts[0].published) {
pubsub.publish('post', {
post: {
mutation: 'DELETED',
data: deletedPosts[0]
}
})
}

return deletedPosts[0]
},
updatePost(parnt, args, { db }, info) {
updatePost(parnt, args, { db, pubsub }, info) {
const { id, data } = args
const post = db.posts.find((post) => post.id === id)
const origPost = { ...post }

if(!post) {
throw new Error("Post Not Found.")
Expand All @@ -115,8 +134,36 @@ const Mutation = {
}
if(typeof data.published === "boolean") {
post.published = data.published

if(origPost.published && !post.published ) {
//delete event
pubsub.publish('post',
{ post: {
mutation: 'DELETED',
data: origPost
}
})
} else if(!origPost.published && post.published) {
//created
pubsub.publish('post',
{ post: {
mutation: 'CREATED',
data: post
}
})
}
} else if(post.published) {
//updated
pubsub.publish('post',
{ post: {
mutation: 'UPDATED',
data: origPost
}
})
}



return post;
},
createComment(parent, args, { db, pubsub }, info){
Expand Down
2 changes: 1 addition & 1 deletion src/resolvers/Subscription.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ const Subscription = {
// next we have to publish newly created post
// this will be done when the post create mutation is run, see Mutations.createPost()
}
},

}
}

export { Subscription as default }
7 changes: 6 additions & 1 deletion src/schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ type Mutation {
type Subscription {
count: Int!
comment(postId: ID!): Comment!
post: Post!
post: PostSubscriptionPayload!
}

input CreateUserInput {
Expand Down Expand Up @@ -88,4 +88,9 @@ type Comment {
text: String!
author: User!
post: Post!
}

type PostSubscriptionPayload {
mutation: String!
data: Post!
}

0 comments on commit bf20256

Please sign in to comment.