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

Martin Ratinaud
  • 600
  • 5
  • 12

3 Answers3

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
    }
  }
}
Corey
  • 45
  • 1
  • 7
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!

mpowell213
  • 89
  • 6
  • 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 ! – Martin Ratinaud Jun 30 '17 at 09:48
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
}
Vojtech Ruzicka
  • 16,384
  • 15
  • 63
  • 66
Andrija Ćeranić
  • 1,633
  • 11
  • 14