使用GraphQL,是否可以根据条件返回某些字段?例如:
[{
name: "Foo",
age: 38
},
{
name: "Bar",
age: 50
}]
我想始终返回name
,但仅当名称为age
时返回Foo
。结果将是这样:
[{
name: "Foo",
age: 38
},
{
name: "Bar"
}]
答案 0 :(得分:0)
在类型定义中,可以设置类型的必需属性和非必需属性。例如,您的类型可以定义为:
type Person {
name: String!
age: Int
}
您将在以下几行中定义一个查询扩展名:
extend type Query {
getPeople: [Person]
}
解析器代码将在其中具有返回此逻辑不同部分的逻辑的位置。可能是沿着这些路线:
getPeople(obj, input, context) {
// Make a request for the information from db or wherever it is stored
// The sql or api request can do the filtering, if not it can be done after it's saved
const people = context.Users.get.People();
// Map over fields for expected return per user based on logic
const filteredPeople = people.map(person => {
if (person.name === "Foo") {
return { name: person.name, age: person.age }
} else {
return { name: person.name };
}
});
return filteredPeople;
};
简而言之,解析器使您可以修改返回的信息