Fragments, aliases and directives

GraphQL · Practical · 10 min

Fragments are how real client apps keep large queries maintainable.

A fragment is a named, reusable selection on a type:

fragment BookCard on Book { id title cover { url } }
query { featured { ...BookCard }  recent { ...BookCard } }

Fragments let each UI component declare the fields it renders (colocation); the page query spreads the fragments of its children. Relay and Apollo's fragment masking build on exactly this.

Aliases rename a field in the response. They are required when you request the same field twice with different arguments, because both results would otherwise land on the same JSON key:

{ small: avatar(size: 64) { url }  large: avatar(size: 512) { url } }

Inline fragments ... on Type { } select fields only when the object has that concrete type; you will use them with interfaces and unions.

The built-in directives @include(if:) and @skip(if:) toggle selections, @deprecated marks schema elements, and @specifiedBy documents custom scalars. Servers may define their own directives.

Validation checks that fragments are used, that spreads are possible for the type, and that fields with the same response key do not conflict.

Example

fragment UserChip on User {
  id
  name
  avatar(size: 32) { url }
}

query ProjectPage($id: ID!) {
  project(id: $id) {
    owner { ...UserChip }
    members(first: 20) { ...UserChip }
    thumb: image(width: 200) { url }   # alias: same field,
    hero: image(width: 1600) { url }   # different arguments
  }
}

Remember

  • Fragments name reusable selections on a type
  • Aliases are needed for the same field with different arguments
  • Colocate fragments with the components that render them

Watch out for

  • Requesting the same field twice with different arguments without aliases: a validation conflict.

Check yourself

  1. Why must `image(width: 200)` and `image(width: 1600)` in one selection use aliases?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: graphql.org/learn/queries/#fragments