【问题标题】:Retrieving single and multiple objects via GraphQL通过 GraphQL 检索单个和多个对象
【发布时间】:2021-05-26 02:37:49
【问题描述】:

我使用 Apollo 和 GraphQL 还不到几周,我想通过 GraphQL 检索多个对象,但它不允许我这样做。

查询为:

const GET_ALL_PURCHASES_QUERY = (statusOfPurchase) => {
  return gql`
  query {
    getAllPurchases(statusOfPurchase: "${statusOfPurchase}") {
      id
      customerInformation {
        customerName
        customerEmailAddress
      }
      createdAt
      updatedAt
    }
  }
`
}

...在架构中:

const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    getAllPurchases: {
      type: PurchaseType,
      args: {
        statusOfPurchase: {
          type: new GraphQLNonNull(GraphQLString)
        }
      },
      resolve(parent, args) {
        return PurchasesModel.schemaForPurchases.find({
          statusOfPurchase: args.statusOfPurchase
        }).limit(10)
          .then(purchases => {
            console.log('Schema:getAllPurchases()', purchases)
            return purchases
          })
      }
    }
  }
})

通过终端在节点中的结果是:

Schema:getAllPurchases() [
  {
    _id: 60351a691d3e5a70d63eb13e,
    customerInformation: [ [Object] ],
    statusOfPurchase: 'new',
    createdAt: 2021-02-23T15:08:25.230Z,
    updatedAt: 2021-02-23T15:08:25.230Z,
    __v: 0
  },
  {
    _id: 60351b966de111716f2d8a6d,
    customerInformation: [ [Object] ],
    statusOfPurchase: 'new',
    createdAt: 2021-02-23T15:13:26.552Z,
    updatedAt: 2021-02-23T15:13:26.552Z,
    __v: 0
  }
]

正确。

但在 Chrome 中的应用程序中,它是一个单独的对象,每个字段的值为 null。

查询为:

const GET_ALL_PURCHASES_QUERY = () => {
  return gql`
  query {
    getAllPurchases {
      id
      customerInformation {
        customerName
        customerEmailAddress
      }
      createdAt
      updatedAt
    }
  }
`
}

...通过对架构进行适当的更改,结果与以前相同,我在 Node 中看到两个对象,但在 Chrome 中看到一个失败的单个对象。

如果我将:return purchases 更改为:return purchases[0],我会在 Chrome 中看到第一个具有正确值的对象。

我应该如何返回多个对象?

【问题讨论】:

    标签: node.js graphql


    【解决方案1】:

    getAllPurchases 字段的类型在架构中设置为 PurchaseType。您想使用new GraphQLList(PurchaseType) 将返回类型设为购买列表。这就是为什么当您尝试使用架构时,如果类型错误,它会返回 null,但如果您确实返回单个元素,则会正确返回购买。

    请参阅 the graphql docs 以获取此示例。

    【讨论】:

    • 亚历克斯,非常感谢。
    猜你喜欢
    • 2012-03-04
    • 2017-04-22
    • 2019-11-27
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 2018-03-11
    相关资源
    最近更新 更多