使用GQLObject作为变异的arg?

时间:2017-09-24 13:20:30

标签: node.js reactjs graphql react-apollo

我在服务器端(nodeJS)上有以下变异(导入RequiredDataType):

mutationA: {
      type: MutationResponseType,
      args: {
        id: {
          type: new GraphQLNonNull(GraphQLString)
        },
        name: {
          type: new GraphQLNonNull(GraphQLString)
        },
        requiredData: {
          type: new GraphQLNonNull(new GraphQLList(RequiredDataType))
        }
      },
      async resolve(parentValue, {
        id,
        name,
        requiredData
      }, req) {
         // Some Magic Code
      }
    },

RequiredDataType编码如下(导入所有GraphQL内容:)):

const RequiredDataType = new GraphQLObjectType({
  name: 'RequiredDataType',
  fields: {
    name: {
      type: GraphQLString
    },
    value: {
      type: GraphQLString
    },
    required: {
      type: GraphQLBoolean
    }
  }
});
module.exports = RequiredDataType;

当我使用此代码时,我收到以下错误:"模块初始化错误:错误"

如果我将变异中的RequiredDataType更改为GraphQLString,它可以正常工作,但我无法使用我需要的对象:)

最后,我将发送和处理以下数据结构:

{
"name": "Hallo"
"id": "a54de3d0-a0a6-11e7-bf70-7b64ae72d2b6",
 "requiredData": [
 {
 "name": "givenName",
 "value": null,
 "required": true
 },
 {
 "name": "familyName",
 "value": null,
 "required": false
 }
 ]
}

在客户端(reactJS与apollo-client)我使用以下gql-tag代码:

export default gql`
  mutation MutationA($id: String!, $name: String!, $requiredData: [RequiredDataType]!){
    mutationA(id: $id, name: $name, requiredData: $requiredData) {
          id,
          somethingElse
      }
    }
`;

但首先它崩溃了服务器上的变异声明。因此,不可能将GQLObject用作突变的参数或代码中的错误在哪里?

感谢您的帮助!

最佳,

费边

1 个答案:

答案 0 :(得分:1)

不幸的是,不能使用某种类型代替输入,也不能使用输入来代替类型。这是设计的。来自official specification

  

字段可以定义客户端使用查询传递的参数,   配置他们的行为。这些输入可以是字符串或枚举,但是   他们有时需要比这更复杂。

     

上面定义的对象类型不适合在这里重复使用,   因为对象可以包含表示循环引用的字段或   对接口和联合的引用,两者都不合适   用作输入参数。出于这个原因,输入对象有一个   系统中的单独类型。

您可以查看this answer以了解有关为什么

的详细信息

您需要将RequiredDataType定义为GraphQLInputObjectType,而不是GraphQLObjectType,以使您的突变工作。如果您还需要它作为GraphQLObjectType,则需要将它们声明为两个单独的类型 - 类似RequiredDataTypeRequiredDataInput