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.
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
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:
interface Vehicle {
numberOfWheels: Int!
color: String!
}Then, you have your object types implement this interface:
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:
union SearchResult = Book | AuthorHere, 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.
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:
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 theifargument istrue.@skip(if: Boolean): Skips the field or fragment if theifargument istrue.
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.
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:
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
- GraphQL Official Documentation on Fragments: https://graphql.org/learn/queries/#fragments
- GraphQL Official Documentation on Interfaces and Unions: https://graphql.org/learn/schema/#interfaces
- GraphQL Official Documentation on Directives: https://graphql.org/learn/queries/#directives
- Apollo GraphQL Documentation on Fragments: https://www.apollographql.com/docs/react/data/fragments/
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
Mediahas common fields:idandtitle. - The types
MovieandTVShowboth implement theMediainterface. Moviehas an additional field:durationInMinutes: Int.TVShowhas additional fields:numberOfSeasons: Intandepisodes: [Episode].- A
SearchResultunion can return one of three types:Movie,TVShow, orActor. - The
Actortype has the fieldsid,name, andbio. - A root field
search(query: String!)returns a list ofSearchResultitems.
Your Task:
- Define a reusable fragment named
ActorDetailsthat selects an actor'sid,name, andbio. - Create a query named
UniversalSearch. - This query must accept two variables:
$queryStringof typeString!and$fetchEpisodesof typeBoolean!. - Query the
searchfield using the$queryStringvariable. - For each result returned by the
searchfield, you must:
a. Request the__typenameto identify the object's type.
b. For results that are aMediatype (MovieorTVShow), fetch the commonidandtitlefields.
c. Using an inline fragment, fetch thedurationInMinutesfield, but only if the result is aMovie.
d. Using an inline fragment, fetch thenumberOfSeasonsfield, but only if the result is aTVShow.
e. Conditionally include theepisodesfield (with each episode'sidandtitle) forTVShowresults. This field should only be fetched if the$fetchEpisodesvariable istrue.
f. For results of typeActor, apply theActorDetailsfragment 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.
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
}
}
}