将自定义类型列表传递给GraphQL突变

时间:2017-09-13 23:20:27

标签: javascript node.js mongoose graphql apollo

我的应用程序的目标是让用户能够保存和调用要填写和编辑的表单列表。一个用户将拥有多种形式,单个表单将由多个字段组成。

如果我的类型设置如下,例如:

const FormType = new GraphQLObjectType({
  name: 'FormType',
  fields: {
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    email: { type: GraphQLString }
  }
});
const UserType = new GraphQLObjectType({
  name: 'UserType',
  fields: {
    id: { type: GraphQLID },
    email: { type: GraphQLString },
    firstName: { type: GraphQLString, default: '' },
    lastName: { type: GraphQLString, default: '' },
    phone: { type: GraphQLString, default: '' },
    forms: { type: new GraphQLList(FormType) }
  }
});

我的突变是这样的:

const mutation = new GraphQLObjectType({
  name: 'Mutation',
  fields: {
    saveForm: {
      type: UserType,
      args: {
        userID: { type: GraphQLID },
        form: { type: FormType } // ???
      },
      resolve(parentValue, { userID, form }) {
        // I'll figure out what to do here when the time comes
      }
    }
  }
});

我似乎无法创建适用于GraphQLList的变异。我一直收到这个错误:

  

错误:Mutation.saveForm(form :)参数类型必须是输入类型但是   得到:FormType。

...我的研究告诉我的意思是FormType需要GraphQLInputObjectType。当我相应地更改它时,我得到错误:

  

错误:Mutation.saveForm(form :)参数类型必须是输出类型但是   得到:FormType。

所以没有什么真正改变。有谁知道这个问题的一个有效例子吗?

1 个答案:

答案 0 :(得分:0)

您遇到的问题是,虽然您已将输入类型正确地更改为GraphQLInputObjectType,但也会将字段UserType.forms的类型更改为输入类型 - 请记住{{ 1}}是输出类型。在这里,您需要制作UserTypeFormType,并在适当的位置使用每个。

另外:为什么您需要表单的完整输入类型?如果只传入ID,它的功能是否同样好?或者,如果意图是FormInputType表示表单数据,为什么需要ID?另外,也许它可以更好地命名为FormType

最后,虽然我认为这提供了一个答案,但您的问题并没有为最小,完整和可验证的示例提供完全剪切+可粘贴的代码,以便我可以轻松检查。