【问题标题】:Field args rejected when return a function not object返回函数而不是对象时,字段参数被拒绝
【发布时间】:2017-04-30 23:48:41
【问题描述】:

我想问一下 GraphQL 此代码将失败,并显示错误

错误:Mutation.addUser args 必须是一个以参数名称作为键的对象。

这里是代码

const Schema = new GraphQLObjectType({
  name: "Mutation",
  description: "Mutation schema",
  fields() {
    return {
      // Add user
      addUser: {
        type: UserSchema,
        args: () => {
          return {
            firstName: {
             type: GraphQLString
            }
          };
        },
        resolve(_, args){
          return Db.models.user.update( () => {
            return _.mapValues(args, (v, k) => {
              return args[k];
            });
          }, {
            returning: true
          });
        }
      }

    };
  }
});

但是,这段代码完美运行

const Schema = new GraphQLObjectType({
  name: "Mutation",
  description: "Mutation schema",
  fields() {
    return {
      // Add user
      addUser: {
        type: UserSchema,
        args: {
          firstName: {
            type: GraphQLString
          },
          lastName: {
            type: GraphQLString
          }
        },
        resolve(_, args){
          return Db.models.user.update( () => {
            return _.mapValues(args, (v, k) => {
              return args[k];
            });
          }, {
            returning: true
          });
        }
      }

    };
  }
});

为什么args 不能从函数返回对象?

【问题讨论】:

    标签: javascript graphql graphql-js


    【解决方案1】:

    fields 本身可以是一个函数,因此在其中包含另一个函数来定义 args 有点多余。

    将它们作为函数的目的是能够定义需要相互引用的类型,或者需要在字段中引用自身的类型。

    所以只有fields 作为一个函数就可以了。

    【讨论】:

    • 你能给我一个例子来实现这个吗?
    • @HabibRohman 您需要哪个部分的示例?在您发布的代码中,fields 本身就是一个函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 2021-09-11
    • 2015-11-26
    相关资源
    最近更新 更多