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.

 

200’s only : Monitor failed and slow GraphQL requests in production

While GraphQL has some features for debugging requests and responses, making sure GraphQL reliably serves resources to your production app is where things get tougher. If you’re interested in ensuring network requests to the backend or third party services are successful, try LogRocket.https://logrocket.com/signup/

LogRocket is like a DVR for web apps, recording literally everything that happens on your site. Instead of guessing why problems happen, you can aggregate and report on problematic GraphQL requests to quickly understand the root cause. In addition, you can track Apollo client state and inspect GraphQL queries' key-value pairs.

LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. .
Adhithi Ravichandran Software Consultant, Pluralsight Author, Speaker, React Native/React/GraphQL Dev & Indian Classical Musician http://adhithiravichandran.com/

Leave a Reply