Do GraphQL fields use polymorphism based on passed arguments?

I would like to ask the following queries

{ // return all individuals individuals { id } } // return ONE individual by id individuals(id:"123") { id } } 

note that the request name is the same, only different parameters.

Today, the only workaround I found is to define different query names.

How to identify polymorphic queries? Is it possible?

+6
source share
1 answer

The fields available at the root of your GraphQL query are defined in the GraphQL schema as fields in the root type of the query, usually simply called Query . This type is exactly the same as any other type of GraphQL object in the schema. Therefore, this question can be reformulated as follows:

Do GraphQL fields have the ability to return different results based on the arguments or arguments passed to?

The short answer is no. One of the important properties of GraphQL is that a certain field must always return the same type; this means that the field returning the array should always return the array, and the field returning the type of the object should always return this particular type, regardless of the arguments passed to.

However, there are several ways to achieve similar results in order to avoid having to create too many different named fields:

  • GraphQL fields may have optional arguments. For example, if you have a field named individuals , you can use optional arguments to provide various filters, for example: individuals(search: "Dan") or individuals(status: "admin") , or individuals (without arguments) or individuals(status: "admin", search: "Dan") (both arguments provided immediately.
  • GraphQL fields can return a union of several types of objects. Therefore, if your field can return several different types of things, you can use union. This is presented in the SearchResult example in the docs: http://graphql.org/learn/schema/#union-types Unfortunately, this does not apply here, since you cannot have an array union with an object type.

In many cases, you need to create multiple fields, because GraphQL does not currently have method overloads or polymorphism.

+6
source

Source: https://habr.com/ru/post/1011566/


All Articles