Learn GraphQL · 5/15

Advanced Query Features: Keeping It DRY

6 min read

Advanced Query Features: Keeping It DRY 💧

Welcome back! So you've mastered the basics of GraphQL queries, but you might be noticing some... repetition. Your queries are getting longer, and you're starting to feel like you're writing the same thing over and over. Fear not, for this guide will introduce you to the advanced features of GraphQL that will help you keep your queries DRY (Don't Repeat Yourself) and take your data-fetching skills to the next level.


1. Fragments: Reusable Chunks of Query Logic 🧩

The Problem: As your application grows, you'll find yourself requesting the same set of fields on a particular type in multiple places. Copying and pasting these fields is not only tedious but also error-prone. If you need to add or remove a field, you have to find every place you've used that set of fields and update it. It's like having to manually update your contact information in every single online account you own – nobody has time for that!

The Solution: Fragments are here to save the day! A GraphQL fragment is a reusable set of fields that you can define once and then include in any query or mutation that needs it. Think of it as creating a "data snippet" that you can sprinkle wherever you need it.

How it Works:

You define a fragment using the fragment keyword, give it a name, and specify the type it applies to. Then, within your query, you use the spread operator (...) followed by the fragment name to include the fields from that fragment.

Example: Before Fragments

Imagine you have a blogging application and you want to fetch the author details for both a blogPost and an article.

graphql
query {
  blogPost {
    title
    author {
      name
      bio
    }
  }
  article {
    headline
    author {
      name
      bio
    }
  }
}

Notice the repetition of the author fields. Now, let's clean this up with a fragment.

Example: After Fragments

graphql
fragment AuthorDetails on Author {
  name
  bio
}

query {
  blogPost {
    title
    author {
      ...AuthorDetails
    }
  }
  article {
    headline
    author {
      ...AuthorDetails
    }
  }
}

Much cleaner, right? If you ever need to add the author's avatarUrl to both, you only need to update the AuthorDetails fragment in one place.

Interesting Fact: Fragments can even be nested within other fragments, allowing you to build up complex data requirements from smaller, reusable pieces.


2. Interfaces and Unions: Handling Multiple Data Types 🎭

The Problem: What happens when a field can return different types of objects? For instance, a search result could be a User, a Post, or a Comment. How do you query for the specific fields of each possible type?

The Solution: GraphQL provides two special abstract types to handle this: Interfaces and Unions.

Interfaces

An interface is an abstract type that defines a set of common fields that other types can "implement." It's like a contract that says, "Any type that implements me must have these specific fields."

Real-world Scenario: Think of a Vehicle interface. Both a Car and a Motorcycle are types of vehicles and share common properties like numberOfWheels and color. However, a Car has a numberOfDoors while a Motorcycle has hasSidecar.

Example:

First, you define the interface in your schema:

graphql
interface Vehicle {
  numberOfWheels: Int!
  color: String!
}

Then, you have your object types implement this interface:

graphql
type Car implements Vehicle {
  numberOfWheels: Int!
  color: String!
  numberOfDoors: Int!
}

type Motorcycle implements Vehicle {
  numberOfWheels: Int!
  color: String!
  hasSidecar: Boolean!
}

Now, when you query a field that returns a Vehicle, you can always ask for the fields defined in the Vehicle interface.

Unions

A union is similar to an interface in that it can return one of several object types. However, unlike interfaces, union types don't need to share any common fields.

Real-world Scenario: Imagine a search feature that can return a Book or an Author. These two types don't necessarily share any fields, but you want to be able to get them from a single search query.

Example:

In your schema, you define the union:

graphql
union SearchResult = Book | Author

Here, SearchResult can be either a Book or an Author.


3. Inline Fragments: Querying Abstract Types 🕵️‍♀️

The Problem: So, you're querying a field that returns an interface or a union. You can get the common fields, but what if you want to get fields that are specific to a particular concrete type? How do you tell GraphQL, "If this is a Car, I want the numberOfDoors, but if it's a Motorcycle, I want to know if it hasSidecar"?

The Solution: This is where inline fragments come to the rescue. An inline fragment allows you to conditionally include fields based on the concrete type of the object being returned. You use the spread operator (...) followed by on and the specific type.

Example with an Interface:

Let's go back to our Vehicle example.

graphql
query GetVehicles {
  vehicles {
    # Common fields from the Vehicle interface
    numberOfWheels
    color
    
    # Type-specific fields using inline fragments
    ... on Car {
      numberOfDoors
    }
    ... on Motorcycle {
      hasSidecar
    }
  }
}

Example with a Union:

And for our SearchResult union:

graphql
query Search($text: String!) {
  search(text: $text) {
    __typename # This is a handy meta-field to know the type
    ... on Book {
      title
      author {
        name
      }
    }
    ... on Author {
      name
      books {
        title
      }
    }
  }
}

Funny Exaggeration: Without inline fragments, querying unions and interfaces would be like trying to order a pizza without knowing the toppings. You'd just get a plain dough, and nobody wants that!


4. Directives: Dynamically Altering Execution (@skip & @include) ⏭️

The Problem: Sometimes, you want to conditionally include or exclude a field or a fragment from your query based on a variable. For example, you might want to fetch a user's email address only if the current user has the necessary permissions.

The Solution: Directives provide a way to tell the GraphQL server to alter the execution of a query. The two most common built-in directives are @skip and @include.

  • @include(if: Boolean): Includes the field or fragment only if the if argument is true.
  • @skip(if: Boolean): Skips the field or fragment if the if argument is true.

How it Works:

You can attach these directives to any field or fragment spread.

Example:

Imagine a scenario where you want to fetch a user's friends list, but only if a certain variable, say withFriends, is true.

graphql
query GetUserProfile($userId: ID!, $withFriends: Boolean!) {
  user(id: $userId) {
    name
    # The friends field will only be included if $withFriends is true
    friends @include(if: $withFriends) {
      name
    }
  }
}

Conversely, you could use @skip:

graphql
query GetUserProfile($userId: ID!, $withoutFriends: Boolean!) {
  user(id: $userId) {
    name
    # The friends field will be skipped if $withoutFriends is true
    friends @skip(if: $withoutFriends) {
      name
    }
  }
}

This dynamic approach can help you avoid making multiple, slightly different queries for different scenarios. It's like having a secret switch to turn parts of your query on or off!

Industry Practice: While you can use both @include and @skip, having both allows for more readable and logical queries. For instance, you can use the same boolean variable to include one field and skip another, making your intentions clearer.


📚 Extra Reading

Challenge

You are building a query for a media application. Your task is to construct a single GraphQL query that searches for different types of content and dynamically includes fields based on runtime variables. You will need to use fragments, interfaces, unions, inline fragments, and directives.

Schema Context:

  • An interface Media has common fields: id and title.
  • The types Movie and TVShow both implement the Media interface.
  • Movie has an additional field: durationInMinutes: Int.
  • TVShow has additional fields: numberOfSeasons: Int and episodes: [Episode].
  • A SearchResult union can return one of three types: Movie, TVShow, or Actor.
  • The Actor type has the fields id, name, and bio.
  • A root field search(query: String!) returns a list of SearchResult items.

Your Task:

  1. Define a reusable fragment named ActorDetails that selects an actor's id, name, and bio.
  2. Create a query named UniversalSearch.
  3. This query must accept two variables: $queryString of type String! and $fetchEpisodes of type Boolean!.
  4. Query the search field using the $queryString variable.
  5. For each result returned by the search field, you must:
    a. Request the __typename to identify the object's type.
    b. For results that are a Media type (Movie or TVShow), fetch the common id and title fields.
    c. Using an inline fragment, fetch the durationInMinutes field, but only if the result is a Movie.
    d. Using an inline fragment, fetch the numberOfSeasons field, but only if the result is a TVShow.
    e. Conditionally include the episodes field (with each episode's id and title) for TVShow results. This field should only be fetched if the $fetchEpisodes variable is true.
    f. For results of type Actor, apply the ActorDetails fragment you created.

Expected result

The final query should correctly define and use a fragment for actor details, query a union type using inline fragments to access type-specific fields, and use a directive to conditionally fetch data based on a variable.

graphql
fragment ActorDetails on Actor {
  id
  name
  bio
}

query UniversalSearch($queryString: String!, $fetchEpisodes: Boolean!) {
  search(query: $queryString) {
    __typename
    ... on Media {
      id
      title
    }
    ... on Movie {
      durationInMinutes
    }
    ... on TVShow {
      numberOfSeasons
      episodes @include(if: $fetchEpisodes) {
        id
        title
      }
    }
    ... on Actor {
      ...ActorDetails
    }
  }
}
graphql

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.