Fragments
As queries grow, you start repeating the same group of fields: the fields a "user card" shows, or the fields of a product tile. A fragment is a named, reusable selection set. Define it once, then spread it with ...Name wherever you need those fields.
Defining and spreading a fragment
fragment CityInfo on City {
name
country
population
}on City is the type condition: the fragment can only be used where a City is expected.
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type City { name: String, country: String, population: Int }
type Query { city(code: String!): City }
`);
const cities = {
LIS: { name: 'Lisbon', country: 'Portugal', population: 545796 },
KRK: { name: 'Kraków', country: 'Poland', population: 803282 },
};
const query = `
query CompareCities {
a: city(code: "LIS") { ...CityInfo }
b: city(code: "KRK") { ...CityInfo }
}
fragment CityInfo on City {
name
country
population
}
`;
const result = await graphql({
schema,
source: query,
rootValue: { city: ({ code }) => cities[code] },
});
console.log(JSON.stringify(result.data, null, 2));{
"a": {
"name": "Lisbon",
"country": "Portugal",
"population": 545796
},
"b": {
"name": "Kraków",
"country": "Poland",
"population": 803282
}
}
The response is exactly as if you had written the three fields twice. Fragments are a query-side convenience: the server just expands them.
Mixing fragments and fields
A spread can sit next to ordinary fields, and fragments can include other fragments. Fields that appear more than once are merged:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type User { id: ID, name: String, avatarUrl: String, email: String }
type Comment { text: String, author: User }
type Query { comments: [Comment] }
`);
const ada = { id: '1', name: 'Ada', avatarUrl: '/img/ada.png', email: 'ada@example.com' };
const alan = { id: '2', name: 'Alan', avatarUrl: '/img/alan.png', email: 'alan@example.com' };
const query = `
{
comments {
text
author { ...UserBadge id }
}
}
fragment Avatar on User { avatarUrl }
fragment UserBadge on User { id name ...Avatar }
`;
const result = await graphql({
schema,
source: query,
rootValue: { comments: [{ text: 'Great post!', author: ada }, { text: 'Thanks', author: alan }] },
});
console.log(JSON.stringify(result.data, null, 2));{
"comments": [
{
"text": "Great post!",
"author": {
"id": "1",
"name": "Ada",
"avatarUrl": "/img/ada.png"
}
},
{
"text": "Thanks",
"author": {
"id": "2",
"name": "Alan",
"avatarUrl": "/img/alan.png"
}
}
]
}
id was requested twice (directly and through UserBadge) but appears once.
Inline fragments
A fragment without a name, written ... on Type { … }, is an inline fragment. On a concrete type it just groups fields, but its real job is choosing fields by type when a field can return several types (interfaces and unions, later in the course):
{
search(text: "rust") {
__typename
... on Book { title }
... on Author { name }
}
}Fragment mistakes the validator catches
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type City { name: String }
type Country { code: String }
type Query { city: City }
`);
const queries = [
// defined but never used
'{ city { name } } fragment Unused on City { name }',
// used on the wrong type
'{ city { ...CountryInfo } } fragment CountryInfo on Country { code }',
// spread of a fragment that doesn't exist
'{ city { ...Missing } }',
];
for (const source of queries) {
const result = await graphql({ schema, source, rootValue: {} });
console.log(result.errors[0].message);
}Fragment "Unused" is never used.
Fragment "CountryInfo" cannot be spread here as objects of type "City" can never be of type "Country".
Unknown fragment "Missing".
Tip: In front-end apps (Apollo Client, Relay, urql) each component often declares a fragment for the data it renders, and the page query combines them. This is called fragment colocation: a component's data needs live next to its code.
Test yourself
How do you use a fragment named PostFields inside a selection set?
#PostFields...PostFields@PostFields&PostFields
What does on City in fragment CityInfo on City specify?
- The variable type
- The type the fragment can be applied to
- The fragment's return value
- The resolver name
What happens to a fragment that is defined but never used?
- It is silently ignored
- It is executed anyway
- Validation fails with an error
- It becomes the default query