[GraphQL] Fragments, Arguments, and Aliases

Fragments

Fragments are a handy feature to help to improve the structure and reusability of your GraphQL code. A fragment is a collection of fields on a specific type.

Example for the following type:

1
2
3
4
5
6
7
8
type User {
name: String!
age: Int!
email: String!
street: String!
zipcode: String!
city: String!
}

Here, we could represent all the information that relates to the user’s physical address into a fragment:

1
2
3
4
5
6
7
8
9
10
11
12
13
fragment addressDetails on User {
name
street
zipcode
city
}

// Then reuse the addressDetails in query
{
allUsers {
... addressDetails
}
}

Parameterizing Fields with Arguments

Specify default values for arguments.

1
2
3
4
5
6
7
8
9
10
11
12
13
type Query {
allUsers: [User!]!
}

type User {
name: String!
age: Int!
}

// Add argument
type Query {
allUsers(olderThan: Int = -1): [User!]!
}

This olderThan argument can now be passed into the query using the following syntax:

1
2
3
4
5
6
{
allUsers(olderThan: 30) {
name
age
}
}

Named Query Results with Aliases

GraphQL lets you send multiple queries in a single request. However, since the response data is shaped after the structure of the fields being requested, you might run into naming issues when you’re sending multiple queries asking for the same fields:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
User(id: "1") {
name
}
User(id: "2") {
name
}
}

// Use alias
{
first: User(id: "1") {
name
}
second: User(id: "2") {
name
}
}

Result:

1
2
3
4
5
6
7
8
{
"first": {
"name": "Alice"
},
"second": {
"name": "Sarah"
}
}

More types

Object & Scalar Types

  • Scalar types represent concrete units of data. String, Int, Float, Boolean, and ID.
  • Object types have fields that express the properties of that type and are composable.

Enums

1
2
3
4
5
6
7
8
9
enum Weekday {
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
}

Interface
An interface can be used to describe a type in an abstract way. It allows you to specify a set of fields that any concrete type, which implements this interface, needs to have.

1
2
3
4
5
6
7
8
9
interface Node {
id: ID!
}

type User implements Node {
id: ID!
name: String!
age: Int!
}

Union Types
Union types can be used to express that a type should be either of a collection of other types. They are best understood by means of an example.

1
2
3
4
5
6
7
8
9
10
11
type Adult {
name: String!
work: String!
}

type Child {
name: String!
school: String!
}

union Person = Adult | Child
1
2
3
4
5
6
7
8
9
10
11
{
allPersons {
name # works for `Adult` and `Child`
... on Child {
school
}
... on Adult {
work
}
}
}