繁体   English   中英

GraphQL.js Node / Express:如何将对象作为GraphQL查询参数传递

[英]GraphQL.js Node/Express: How to pass object as GraphQL query argument

我的目标是能够在GraphQL查询中将对象作为参数传递。

目标:

{
    accounts (filter: 
      {"fieldName": "id",
      "fieldValues":["123"],
      "filterType":"in"}){
        id
      }
 }

错误:

"message": "filterType fields must be an object with field names as keys or a function which returns such an object."

我尝试了一些不同的方法,但这似乎是最接近潜在的解决方案。

架构:

const filterType = new GraphQLObjectType ({
  name: 'filterType',
  fields: {
    fieldName: { type: GraphQLString },
    fieldValues: { type: GraphQLString },
    filterType: { type: GraphQLString },
  }
})

const QueryType = new GraphQLObjectType({
  name: 'Query',
  fields: () => ({
    accounts: {
      type: new GraphQLList(accountType),
      args: {
        filter: { type: new GraphQLInputObjectType(filterType) },
      },
      resolve: (root, args, { loaders }) => loaders.account.load(args),
    },

  }),
});

您没有将filterType定义为对象类型,然后将其包装在输入类型中,您可以将其创建为输入类型:

const filterType = new GraphQLInputObjectType({
  name: 'filterType',
  fields: {
    fieldName: { type: GraphQLString },
    fieldValues: { type: GraphQLString },
    filterType: { type: GraphQLString },
  }
})

const QueryType = new GraphQLObjectType({
  name: 'Query',
  fields: () => ({
    accounts: {
      type: new GraphQLList(accountType),
      args: {
        filter: { type: filterType },
      },
      resolve: (root, args, { loaders }) => loaders.account.load(args),
    },
  }),
});

您还需要在查询时声明其类型,如@ piotrbienias的回答所示。

我在这里找到了解决方案。 https://github.com/mugli/learning-graphql/blob/master/7.%20Deep%20Dive%20into%20GraphQL%20Type%20System.md#graphqlinputobjecttype

架构:

const filterType = new GraphQLInputObjectType({
  name: 'filterType',
  fields: {
    fieldName: { type: GraphQLString },
    fieldValues: { type: GraphQLString },
    filterType: { type: GraphQLString },
  }
})

const QueryType = new GraphQLObjectType({
  name: 'Query',
  fields: () => ({
    accounts: {
      type: new GraphQLList(accountType),
      args: {
        filter: { type: filterType },
      },
      resolve: (root, args, { loaders }) => {
        return loaders.account.load(args)},
    },
  }),
});

问题出现在查询中,我在对象参数中将键和值都作为字符串。

正确查询:

{
  accounts(filter: {fieldName: "id", fieldValues: "123", filterType: "in"}) {
    id
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM