【问题标题】:Passing Objects as Argument to GraphQL Mutation (graphql-request)将对象作为参数传递给 GraphQL Mutation (graphql-request)
【发布时间】:2021-03-30 12:49:44
【问题描述】:

我在前端有一个非常基本的 graphql 突变,我发送到我的后端。我在graphql-request 上使用this code 作为指导。

使用原语它可以工作:

const mutation = gql`
    mutation EditArticle($id: ID!, $title: String) {
      editArticle(id: $id, title: $title) {
        id
      }
    }
  `

现在我还希望能够改变有关文章的一些元数据,存储在文章内的 meta 对象中:

...,
title: "Hello World",
meta: {
 author: "John",
 age: 32,
 ...
}

所以我的问题是:如何在使用 graphql-request 从前端发出请求时将非原始对象类型作为参数传递给突变?

我已经尝试过这样的事情:

const Meta = new GraphQLObjectType({
    name: "Meta",
    fields: () => ({
      id: { type: GraphQLID },
      name: { type: GraphQLString },
      age ....
    }),
  })
   
const mutation = gql`
    mutation EditArticle($id: ID!, $title: String, $meta: Meta) { //??? I don't seem to get what goes here? 
      editArticle(id: $id, title: $title, meta: $meta) {
        id
      }
    }
  `

我也用GraphQLObjectType 尝试过,但我认为我在这里出错了(因为这是前端)。

PS:我查看了this answer,但我不明白/相信那里的解决方案可能不完整。

【问题讨论】:

  • 在您的架构中查看editArticle 参数的类型。很可能它应该类似于MetaInput。它必须是 input 类型,而不是输出类型。
  • 非常感谢,我想我现在明白了。所以 MetaInput 类型是我在服务器上定义的,但在客户端我可以写它的类型为 MetaInput 并且不需要在客户端再次定义它,正如我现在所理解的那样?
  • 是的,如果你使用express-graphql,当然服务器端是依赖于实现的(你不一定需要自己构造一个new GraphQLInputObjectType - 你可能只是解析一个模式定义什么的)。但是在定义查询的前端,您只需按名称引用它,您不必做任何额外的事情。
  • 好吧,我想这是让我感到困惑的一点!太感谢了。如果您只是将其写为答案,我肯定会接受:)

标签: javascript graphql graphql-js express-graphql graphql-mutation


【解决方案1】:

您需要在服务器端架构中定义输入对象类型,例如

input MetaInput {
  name: String
  author: String
  release: Date
}

并在editArticle 定义中使用它

extend type Mutation {
  editArticle(id: ID!, title: String, meta: MetaInput): Article
}

那么你也可以在mutation EditArticle的客户端定义中引用MetaInput类型。

【讨论】:

  • 非常感谢,这很有帮助!
猜你喜欢
  • 2018-12-08
  • 2017-10-26
  • 2017-01-02
  • 2017-01-26
  • 2017-09-27
  • 2023-01-26
  • 2019-01-13
  • 2017-02-05
  • 2017-08-01
相关资源
最近更新 更多