GraphQL

Write an awesome doc for GraphQL. A very nice an practical one extracted from GraphQL official documentation.

View on GitHub

Queries

Don’t Repeat Yourself (DRY) – Named Fragments

We need to reuse parts of our queries. For sake of having an easier time to develop and maintain we can use fragments. It shines where we have:

Imagine in our todo app we need to show a lot more data to the user than what we show them in index page. So our client want to be able to query specify common fields in a fragment and expand it in the query for a single todo.

Fetch todos for index page and a single todo in details page

You need to define fragments in your client-side app – ref. And as yo how you can use this logic in your ReactJS app you can look at this YouTube video.

[!TIP]

You can also pass variables to your fragment (learn more here).

Work with generic types and concrete ones – inline fragments

So assume we have 3 interfaces:

  1. Fleet which is a generic type.
  2. Truck which is a fleet with a concrete interface,
  3. Van which is also a fleet with a concrete interface.

Now we wanna fetch data from a shared endpoint. We will ask for mileage which is something defined in Fleet. And we need to get some specific fields based on the returned interface type:

Select fields based on type with inline fragment

[!TIP]

Named fragments can also be used and this is not restricted to inline fragments.

Variable

By using variables:

Centralized data transformation

[!NOTE]

You can define any custom type, but you should define it in a representable way, in a format suitable for communication between the client and server.

Aliases

You cannot query for the same field with different arguments. Solution? Aliases:

They let you rename the result of a field to anything you want. **Another use case** is when your client wants to rename fields to something that is tailor to their specific programming language.

![Aliases](/graphql-js-ts/docs/assets/aliases.png)

Directives

Now imagine you need to fetch data based on some conditions that will be provided by user:

Dynamic table
Ref for the picture
query GetProducts(
  $filter: FilterProductsInput
  $withLastTrade: Boolean!
) {
  getProducts(filter: $filter) {
    id
    lastTrade @include(if: $withLastTrade) {
      volume
    }
    # ...
  }
}

We also have another directive which is @skip, but ATM I am failing to see any real world implication for it. But that’s just me and I am pretty sure that there are use cases for @skip too.

[!NOTE]

  • We use directives to not manipulate and change our query dynamically.
  • Server implementation can also define directives.

Mutations

Side effects

Order of execution for specified fields

Operation type Execution order Implications
query. Parallel/concurrent.  
mutation. Series. E.g. if you call incrementCredits twice they run one after another.

Metadata