如何 return GraphQL 中的对象数组,可能使用与 return 单个对象相同的端点?

How to return an array of objects in GraphQL, possibly using the same endpoint as the one that returns a single object?

我正在制作一个 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
    }
  }
}

如有任何帮助,我们将不胜感激。

汽车和汽车列表实际上是两种不同的类型。一个字段不能一次解析为单个 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 以获取更多示例和选项。