5

I have a very simple model with post that embeds several comments

I wondered how I should do a mutation to add a new comment to the post

As I already have queries defined to get back a postwith a given id, I wanted to try to have the following mutation syntax working

mutation {
  post(id: "57334cdcb6d7fb172d4680bb") {
    addComment(data: {
      text: "test comment"
    })
  }
}

but I can't seem to find a way to make it work. Even if I'm in a mutation, output type being a post addComment is seen as a field post should have.

Do you guys have any idea ?

Thanks

2

3 Answers 3

1

You can't embed fields into other fields like that.

You would create a new input object for your post mutation

input CommentInput {
 text: String
}

type Mutation {
 post(id: ID!, addComment: CommentInput): Post
}

In your resolver you look for the addComment variable and call the addComment resolver with the arguments.

Your mutation would be

mutation {
  post(id: "57334cdcb6d7fb172d4680bb", 
    addComment: {
      text: "test comment"
    }) {
    id
    comment {
      text
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I could be wrong but you may want to just create a separate updatePost mutation that accepts the post id as an argument

type Post {
   comments: [ Comment ]
}

input PostInput {
   comments: [ CommentInput ]
}

type Mutation {
   updatePost( id: ID!, input: PostInput ): Post
}

The updatePost mutation here takes the id of the post and the updated post object as arguments and returns a type Post. So I would use this like so:

mutation {
  updatePost( id: '1234', input: { comments: []) {
    id
  }
}

Hope this helps!

1 Comment

Actually this is not exactly what I want as what you propose would replace whatever is in comments by what you provide. What I need is a way to use an existing other mutation within a mutation. Thanks anyway !
0

Maybe you could create addComment mutation that you pass post id to and then return a Post.

type Mutation {
   addComment( postId: ID!, input: CommentInput ): Post
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.