Har*_*uri 3 javascript node.js graphql graphql-js express-graphql
我正在制作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;
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
测试查询及其各自的结果:
查询1
{
cars(id:"1"){
name
}
}
Run Code Online (Sandbox Code Playgroud)
查询1响应(成功)
{
"data": {
"cars": {
"name": "Honda"
}
}
}
Run Code Online (Sandbox Code Playgroud)
查询2
{
cars{
name
}
}
Run Code Online (Sandbox Code Playgroud)
查询2响应(失败)
{
"data": {
"cars": {
"name": null
}
}
}
Run Code Online (Sandbox Code Playgroud)
任何帮助将非常感激。
汽车和汽车清单实际上是两种不同的类型。一个字段一次不能解析为一个Car对象,而另一个不能解析为一个Car对象数组。
您的查询返回null,name因为您告诉它该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;
}
}
Run Code Online (Sandbox Code Playgroud)
另外,您可以将其分为两个单独的查询:
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),
}
Run Code Online (Sandbox Code Playgroud)
检查文档以获取更多示例和选项。
| 归档时间: |
|
| 查看次数: |
5163 次 |
| 最近记录: |