graphql - 在突变中使用查询 - 创建嵌套对象

时间:2016-05-12 16:01:27

标签: nested graphql mutation graphql-js

我有一个非常简单的模型post嵌入了多个comments

我想知道如何进行变异以向comment

添加新的post

由于我已经定义了查询以获取具有给定post的{​​{1}},我想尝试使用以下变异语法

id

但我似乎无法找到让它发挥作用的方法。即使我处于变异状态,输出类型为mutation { post(id: "57334cdcb6d7fb172d4680bb") { addComment(data: { text: "test comment" }) } } addComment也会被视为字段post应该有的。

你们有什么想法吗?

由于

3 个答案:

答案 0 :(得分:0)

我可能错了,但您可能只想创建一个单独的 updatePost 变种,将post id作为参数接受

type Post {
   comments: [ Comment ]
}

input PostInput {
   comments: [ CommentInput ]
}

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

此处的updatePost变异将post的id和更新的post对象作为参数,并返回Post类型。 所以我会像这样使用它:

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

希望这有帮助!

答案 1 :(得分:0)

也许你可以创建{post} id传递的addComment突变,然后返回一个帖子。

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

答案 2 :(得分:0)

您不能将字段嵌入到类似的其他字段中。

您将为您的后期突变创建一个新的输入对象

input CommentInput {
 text: String
}

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

在您的解析器中,查找addComment变量,并使用参数调用addComment解析器。

您的突变将会是

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