im trying to perform a query like this:
{
people{
pet{
name
}
}
}
result:
{
"people": {
"pet": null
}
},
{
"people": {
"pet": {
name: "steve"
}
}
}
What i want is to get only people that contains a pet, is there any way to achieve this not coding on my resolver ?
Actually, it is possible with the filter: { pet: {ne: null} }
filtering:
query allPeople(filter: { people: { pet: {ne: null} } }) {
people {
pet
}
}
This is not possible the way you describe. GraphQL will call resolve functions to fetch the data. If you don't want certain data in your response, you have to filter it somewhere on the server. The only thing you have control over is the query, the schema and the resolve functions.
There is no way to express your requirement purely in the query. If you put it in the schema, you would no longer be able to query for people without pets. So the only way to do it is to write it in your resolve function. You could for example add a boolean argument called hasPet
to your people field, and do this in the resolver:
people(root, { hasPet }){
// get allPeople
if (typeof hasPet === 'undefined'){
return allPeople
}
return allPeople.filter((person) => person.hasPet() === hasPet)
}
The unfortunate thing is that this will require you to 'look ahead' and figure out if a person has a pet in the first place, but if you cache backend or DB requests with something like DataLoader, this isn't actually costly, because you would have to fetch the pet anyway. This way you just fetch it a bit earlier.
If you're fetching your people from a database, it would of course make sense to already filter them there, and not in the resolve function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With