GraphQL.js Node / Express:如何将对象作为GraphQL查询parameter passing

我的目标是能够将一个对象作为parameter passing给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." 

我尝试了几种不同的方法,但是这似乎是最接近潜在的解决scheme。

架构:

 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定义为对象types,然后将其包含在inputtypes中,您可以将其作为inputtypes进行创build:

 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), }, }), }); 

你也想在查询的时候声明它的types,如@ piotrbienias的答案所示。

我在这里find了解决办法。 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)}, }, }), }); 

问题是在查询中,我有对象参数中的键和值作为string。

正确的查询:

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