如何在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检索汽车对象或在不提供任何参数的情况下检索所有汽车.
I am making a GraphQL API where I would be able to retrieve a car object by its id or retrieve all the cars when no parameter is provided.
使用下面的代码,我可以通过提供id作为参数来成功检索单个汽车对象.
Using the code below, I am successfully able to retrieve a single car object by supplying id as a parameter.
但是,在我希望有一组对象的情况下,即当我完全不提供任何参数时,在GraphiQL上将不会得到任何结果.
schema.js
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;
}
}
}
});
测试查询及其相应结果:
Test queries and their respective results:
查询1
{
cars(id:"1"){
name
}
}
查询1响应(成功)
{
"data": {
"cars": {
"name": "Honda"
}
}
}
查询2
{
cars{
name
}
}
查询2响应(失败)
{
"data": {
"cars": {
"name": null
}
}
}
任何帮助将不胜感激.
Any help would be much appreciated.
推荐答案
汽车和汽车列表实际上是两种不同的类型.一个字段一次不能解析为一个Car对象,而另一个不能解析为一个Car对象数组.
A Car and a List of Cars are effectively two separate types. A field cannot resolve to a single Car object one time, and an array of Car object another.
您的查询返回的name
为空,因为您告诉它cars
字段可以解析为单个对象,但是却可以解析为数组.结果,它将在数组对象上寻找一个名为name
的属性,由于不存在该属性,因此它将返回null.
Your query is returning null for the name
because you told it the cars
field would resolve to a single object, but it resolved to an array instead. As a result, it's looking for a property called name
on the array object and since one doesn't exist, it's returning null.
您可以通过两种不同的方式来处理此问题.要将内容保留为一个查询,可以使用filter
而不是find
并将查询的类型更改为列表.
You can handle this in a couple of different ways. To keep things to one query, you can use filter
instead of find
and change the type of your query to a List.
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;
}
}
或者,您可以将其分为两个单独的查询:
Alternatively, you could split this into two separate queries:
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),
}
查看文档以获得更多示例和选项.
Check the docs for more examples and options.
这篇关于如何在GraphQL中返回对象数组,可能使用与返回单个对象相同的端点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!