繁体   English   中英

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

[英]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),
}

查看文档以获取更多示例和选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM