पाठ 7 / 25

Fields, Aliases and Fragments

Reusable selections.

Select, rename and reuse

A query selects fields and nested fields; every leaf must be a scalar or enum. Aliases rename a field in the response so the same field can be requested twice with different arguments. Fragments name a reusable selection on a type and are spread with ...Name; inline fragments (... on Product) select type-specific fields from interfaces and unions. In component-based UIs, each component often declares the fragment of data it needs.

Shape the response

Aliases, fragments, variables and directives make queries reusable and precise.

Three ideas: fields, aliases and fragments; variables and directives; introspection.
Figure 3.1 — Fragments, variables and introspection.

Aliases and fragments

A GraphQL query.

query ProductPage {
  featured: product(id: "7") { ...ProductCard }
  related: product(id: "9") { ...ProductCard }
  search(text: "lamp") {
    __typename
    ... on Product { name price { amount currency } }
    ... on User { name }
  }
}

fragment ProductCard on Product {
  id
  name
  price { amount currency }
}

Request __typename for abstract types

Clients and caches need __typename to know which concrete type each union or interface result is.

त्वरित जाँच: Why use an alias?

  • To request the same field more than once with different arguments
  • To make a field optional
  • To delete a field
  • To change its type
Answer

To request the same field more than once with different arguments — Response keys must be unique.