Reputation: 51435
I would like to define the following queries
{
// return all individuals
individuals {
id
}
}
// return ONE individual by id
individuals(id:"123") {
id
}
}
note that the query name is the same, only the parameters are different.
Today, the only workaround I found is to define different query names.
How can I define polymorphic queries? Is it even possible?
Upvotes: 21
Views: 15285
Reputation: 6147
The fields accessible at the root of your GraphQL query are defined in a GraphQL schema as fields on the root query type, commonly simply named Query
. This type is exactly the same as any other GraphQL Object type in a schema. So this question can be restated as:
Do GraphQL fields have the ability to return different results based on the arguments or argument types passed in?
The short answer is "no". One important property of GraphQL is that a particular field must always return the same type; this means that a field that returns an array must always return an array, and a field that returns an object type must always return that particular type, regardless of the arguments passed in.
However, there are a few ways you can achieve similar results to avoid needing to create too many different named fields:
individuals
, you could use optional arguments to supply different kinds of filters, for example: individuals(search: "Dan")
or individuals(status: "admin")
, or individuals
(with no arguments) or individuals(status: "admin", search: "Dan")
(both arguments provided at once.In many cases though, you will need to create multiple fields because GraphQL doesn't currently have method overloading or polymorphism.
Upvotes: 21