GraphQL SDL – Schema Definition Language Part 2

Tram Ho

Continuing Part one on the GraphQL Schema Definition Language, this article goes on to cover the concepts used to define the GraphQL Schema

1. Interfaces

  • Like the concept of Interface in other languages, in GraphQL, an Interface is an asbstract type can consist of a certain set of fields whose types when implementing it must also include those fields.
  • For example, you have a Character interface that represents any character in Star Wars

    Any type of Implements Characters must have all of the above fields with the same parameters or the same type.
  • For example, the types six here can implement Character

    All three types have all the fields from the Character interface, and also have additional fields like totalCredits , starships , primaryFunction help define specific types of Character.
  • Interfaces are useful when you want to return an object or a set of objects, but they have different fields.
  • For example, the following query will generate an errorQUERY DEFINITION

    CLIENT CALL QUERY

    VARIABLES

    RESULT
  • The hero field returns a Character type, it can be Human or Droid depending on the episode variable. In the above query, you can only specify to return fields that exist in the Character interface, so there is no primaryFunction
  • To request that the fields be returned in a specific object type, use inline fragments

2. Union types

  • For example
  • Whenever we return a type of Search Result in the schema, this SearchResult can be a Human , Droid , or a Starship . The members of a union type need to be of a particular type of object, not an interface or another union
  • When the client side queries a field that returns a union type of SearchResult , we need to use the inline fragment to be able to query any field.CLIENT QERRY

    RESULT
  • The __typename field is a String that helps you to distinguish between object types on the Client
  • In this example, since Human and Droid implement the same interface Character , you can query the common fields of these 2 object types in one place without repeating the same fields for each type, for example below The result is as above:

    Note: The name field must still be specified to Starship because Starship not a Character

3.Input types

  • So far, we’ve only talked about passing a field argument of type scalar like enums or strings. However, you can pass the argument to a complex object. This is extremely useful when you want to pass an entire object to create something.
  • In GraphQL SDL, input types look like common object types but with keyword input instead of type
  • Example using input type in a mutationMUTATION DEFINITION

    VARIABLES

    RESULT

4. Conclusion

Share the news now

Source : Viblo