【问题标题】:How to return an array of objects in GraphQL, possibly using the same endpoint as the one that returns a single object?如何在 GraphQL 中返回一组对象,可能使用与返回单个对象的端点相同的端点?
【发布时间】:2019-03-17 06:57:51
【问题描述】:

我正在制作一个 GraphQL API,我可以在其中通过其 id 检索汽车对象,或者在未提供参数时检索所有汽车。

使用下面的代码,我可以通过提供 id 作为参数成功地检索单个汽车对象。

但是,在我期望一个对象数组的情况下,即当我根本不提供任何参数时,我在 GraphiQL 上没有得到任何结果。

schema.js

let cars = [
  { name: "Honda", id: "1" },
  { name: "Toyota", id: "2" },
  { name: "BMW", id: "3" }
];

const CarType = new GraphQLObjectType({
  name: "Car",
  fields: () => ({
    id: { type: GraphQLString },
    name: { type: GraphQLString }
  })
});

const RootQuery = new GraphQLObjectType({
  name: "RootQueryType",
  fields: {
    cars: {
      type: CarType,
      args: {
        id: { type: GraphQLString }
      },
      resolve(parent, args) {
        if (args.id) {
          console.log(cars.find(car => car.id == args.id));
          return cars.find(car => car.id == args.id);
        }
        console.log(cars);
        //***Problem Here***
        return cars;
      }
    }
  }
});

测试查询及其各自的结果:

查询 1

{
  cars(id:"1"){
    name
  }
}

查询 1 响应(成功)

{
  "data": {
    "cars": {
      "name": "Honda"
    }
  }
}

查询 2

{
  cars{
    name
  }
}

查询 2 响应(失败)

{
  "data": {
    "cars": {
      "name": null
    }
  }
}

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript node.js graphql graphql-js express-graphql


    【解决方案1】:

    汽车和汽车列表实际上是两种不同的类型。一个字段一次无法解析为单个 Car 对象,而另一次解析为 Car 对象数组。

    您的查询为 name 返回 null,因为您告诉它 cars 字段将解析为单个对象,但它解析为数组。结果,它在数组对象上寻找一个名为 name 的属性,由于该属性不存在,所以它返回 null。

    您可以通过几种不同的方式处理此问题。要将事情保留在一个查询中,您可以使用 filter 而不是 find 并将查询类型更改为列表。

    cars: {
      type: new GraphQLList(CarType), // note the change here
      args: {
        id: {
          type: GraphQLString
        },
      },
      resolve: (parent, args) => {
        if (args.id) {
          return cars.filter(car => car.id === args.id);
        }
        return cars;
      }
    }
    

    或者,您可以将其拆分为两个单独的查询:

    cars: {
      type: new GraphQLList(CarType),
      resolve: (parent, args) => cars,
    },
    car: {
      type: CarType,
      args: {
        id: {
          // example of using GraphQLNonNull to make the id required
          type: new GraphQLNonNull(GraphQLString)
        },
      },
      resolve: (parent, args) => cars.find(car => car.id === args.id),
    }
    

    查看docs 了解更多示例和选项。

    【讨论】:

      猜你喜欢
      • 2020-05-09
      • 2017-07-06
      • 1970-01-01
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 1970-01-01
      • 2014-07-17
      相关资源
      最近更新 更多