簡體   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