GraphQL.js Node/Express:如何将对象作为 GraphQL 查询参数传递 [英] GraphQL.js Node/Express: How to pass object as GraphQL query argument

查看:26
本文介绍了GraphQL.js Node/Express:如何将对象作为 GraphQL 查询参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My goal is to be able to pass an object as an argument in a GraphQL query.

目标:

{
    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."

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

I've tried a few different approaches but this seems to be the closest to the potential solution.

架构:

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

  }),
});

推荐答案

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

I have found the solution here. 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)},
    },
  }),
});

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

Problem was in the query, I had the both the keys and values as strings in the object argument.

正确查询:

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

这篇关于GraphQL.js Node/Express:如何将对象作为 GraphQL 查询参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆