Adhithi Ravichandran Software Consultant, Pluralsight Author, Speaker, React Native/React/GraphQL Dev & Indian Classical Musician http://adhithiravichandran.com/

GraphQL fragments explained

2 min read 683

What is a GraphQL fragment?

In this post, we are going to learn about what a fragment is in GraphQL. A GraphQL fragment is a reusable part of the query. In GraphQL, you may run into situations where you need to query for the same fields in different queries. If you notice that your query has many repetitive fields in multiple areas, you can consolidate them into a reusable unit called a fragment.

A GraphQL fragment lets you build multiple fields, and include them in multiple queries. You can think of it as functions in programming languages, that are reusable units.

A GraphQL Fragment is a reusable unit of a GraphQL query, which creates a shared piece of query logic.

The components of a GraphQL fragment

Let’s take a look at the different parts of a GraphQL fragment with a sample structure below:

fragment Name on TypeName {
  field1
  field2
  field3
}

A fragment consists of three unique components:

  • Name: This is the unique name of the fragment (each fragment can have its own name)
  • TypeName: The type of object the fragment is going to be used on. This indicates which nested object, from the GraphQL schema, this fragment is created on
  • Body: The last part is the body of the fragment. The body of the fragment defines the fields that will be queried for

Benefits of using a GraphQL fragment

So why are fragments cool within a GrapQL query?

  • Reusability – With fragments, you can organize your queries into reusable units
  • CachingGraphQL clients make use of fragments, to provide caching options

Creating GraphQL fragments

Let’s learn how to create GraphQL fragments with some examples. For the examples in this blog post, I am using GitHub’s public API and writing queries against it. You can follow along by signing into your GitHub account, and executing the queries from the GitHub GraphQL Explorer.

Notice that we are querying for the same fields inside the owner field multiple times. This is a good place to create a fragment:

{
  googleRepo: repository (owner:"google", name:"WebFundamentals") {
    name
    owner {
      id,
      avatarUrl
      resourcePath
      url
    }
  }
  facebookRepo: repository (owner:"facebook", name:"react") {
    name
    owner {
      id,
      avatarUrl
      resourcePath
      url
    }
  }
}

We can rewrite our query to use a fragment. Fragments are created with the keyword fragment.

We can create a fragment called ownerInfo. While creating fragments we have to let GraphQL know on which field it is created. In our case, we are creating the fragment on the RepositoryOwner field. Within our fragment definition, we can include all the fields that we are querying for on the RepositoryOwner object. We are adding id, avatarUrl, resourcePath and url as fields to our fragment.

// fragment ownerInfo for RepositoryOwner fields
fragment ownerInfo on RepositoryOwner {
  id
  avatarUrl
  resourcePath
  url
}

Using a GraphQL fragment

You can then use the fragment that we created in the previous example, within the query by using the … operator and providing the fragment’s name as shown below:

// GraphQL Query with fragments

{
  googleRepo: repository(owner: "google", name: "WebFundamentals") {
    name
    owner {
      ...ownerInfo //fragment
    }
  }
  facebookRepo: repository(owner: "facebook", name: "react") {
    name
    owner {
     ...ownerInfo //fragment
    }
  }
}

The snippet shown below is the JSON response after using a fragment. Notice, that there won’t be any changes to the response returned with the use of fragments. Fragments simply make your query clean, readable and reusable. It has no effect on the query response that comes back.

// GraphQL JSON Response

{
  "data": {
    "googleRepo": {
      "name": "WebFundamentals",
      "owner": {
        "id": "MDEyOk9yZ2FuaXphdGlvbjEzNDIwMDQ=",
        "avatarUrl": "https://avatars1.githubusercontent.com/u/1342004?v=4",
        "resourcePath": "/google",
        "url": "https://github.com/google"
      }
    },
    "facebookRepo": {
      "name": "react",
      "owner": {
        "id": "MDEyOk9yZ2FuaXphdGlvbjY5NjMx",
        "avatarUrl": "https://avatars3.githubusercontent.com/u/69631?v=4",
        "resourcePath": "/facebook",
        "url": "https://github.com/facebook"
      }
    }
  }
}

Conclusion

I hope you enjoyed writing some GraphQL queries. If you are interested in further learning about GraphQL and getting a big picture overview of GraphQL, you can check out my course GraphQL: The Big Picture on Pluralsight.

Resources:
https://graphql.org/
https://graphql.org/learn/
https://www.graphql.com/

If you have any comments, please post your comments below and share this post with your team and friends.

 

Plug: , a DVR for web apps

LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

.
Adhithi Ravichandran Software Consultant, Pluralsight Author, Speaker, React Native/React/GraphQL Dev & Indian Classical Musician http://adhithiravichandran.com/

Leave a Reply