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?
GraphQL does not inherently support inheritance. There is no syntax that would help you avoid duplication of fields across multiple types. Barring that, you can also utilize a library like graphql-s2s which allows you to utilize inheritance and generic types.
There are three types of operations that GraphQL models: query – a read‐only fetch. mutation – a write followed by a fetch. subscription – a long‐lived request that fetches data in response to source events.
When you're passing arguments in code, it's generally better to avoid constructing the whole query string yourself. Instead, you can use $ syntax to define variables in your query, and pass the variables as a separate map. . then(data => console.
From the point of view of the client, the most common GraphQL operations are likely to be queries and mutations.
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.
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