Graphql queries: Difference between revisions

From wikinotes
Line 40: Line 40:
Example schema }}
Example schema }}


When a collection can contain multiple types,<br>
* Select type-specific fields in heterogenous collections
fragments let you select different fields for different types.
* Concisely describe a group of fields, DRY out queries
* Concisely describe Recursive/Nested nodes


named fragments
<syntaxhighlight lang="graphql">
{
  children {
    ...nodeFields
    children {
      ...nodeFields {
        children {
          ...nodeFields
        }
      }
    }
  }
}
fragment nodeFields on Node {
  id
  text
  colour
  background-colour
}
</syntaxhighlight>
inline fragments
<syntaxhighlight lang="graphql">
<syntaxhighlight lang="graphql">
{
{
Line 62: Line 91:
}
}
</syntaxhighlight>
</syntaxhighlight>
* <code>wheels, passengers</code> are queried on all items
* <code>numSeatbelts,numAirbags</code> is queried on <code>Car</code> items
* <code>numSaddleBags</code> is queried on <code>Motorcycle</code> items
</blockquote><!-- Fragments -->
</blockquote><!-- Fragments -->

Revision as of 03:11, 2 September 2021

Basics

Without Params

Some fields may be implied by the REST API path, so no params are required.

# https://tracking-system/projects/1/graphql
{
  name
  createdAt
}

With Params

Other times, you may need to use parameters in your query.

# https://tracking-system/projects/1/graphql
{
  tasks($name: String){
    status
    createdAt
  }
}
{"name": "clean bathroom"}

Fragments

TODO:

Example schema

  • Select type-specific fields in heterogenous collections
  • Concisely describe a group of fields, DRY out queries
  • Concisely describe Recursive/Nested nodes

named fragments

{
  children {

    ...nodeFields
    children {

      ...nodeFields {
        children {

          ...nodeFields
        }
      }
    }
  }
}


fragment nodeFields on Node {
  id
  text
  colour
  background-colour
}

inline fragments

{
  rentalInventory {
    vehicles {
      wheels               # select on both Car and Motorcycle
      passengers

      ... on Car {         # select on Car items only
        numSeatbelts
        numAirbags
      }

      ... on Motorcycle {  # select on Motorcycle items only
        numSaddleBags
      }
    }
  }
}