GraphQL Exercises
Time to practise! Each exercise has a starter playground that runs as-is and prints a placeholder result, so you can see the format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. Solutions are hidden below each exercise. Try for a few minutes before peeking.
| # | Exercise | Topics |
|---|---|---|
| 1 | Write the query | fields, arguments, aliases |
| 2 | Reuse with a fragment | fragments, variables |
| 3 | A computed field | resolvers, parent object |
| 4 | Add a mutation | mutations, input types |
| 5 | Enum filter | enums, arguments |
| 6 | Union search | unions, inline fragments, __typename |
| 7 | Cursor pagination | connections, pageInfo |
| 8 | Count the fields | AST, visit |
1. Write the query
The schema is ready. Write a query that fetches the name and capital of Japan (code: "JP") and of Kenya (code: "KE") in one request, using the aliases japan and kenya.
Expected: {"japan":{"name":"Japan","capital":"Tokyo"},"kenya":{"name":"Kenya","capital":"Nairobi"}}
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Country { code: ID!, name: String!, capital: String! }
type Query { country(code: ID!): Country }
`);
const countries = {
JP: { code: 'JP', name: 'Japan', capital: 'Tokyo' },
KE: { code: 'KE', name: 'Kenya', capital: 'Nairobi' },
};
const rootValue = { country: ({ code }) => countries[code] };
// TODO: request both countries with aliases
const query = '{ country(code: "JP") { name } }';
const result = await graphql({ schema, rootValue, source: query });
console.log(JSON.stringify(result.data));{"country":{"name":"Japan"}}
Show solution
const query = `{
japan: country(code: "JP") { name capital }
kenya: country(code: "KE") { name capital }
}`;2. Reuse with a fragment
Rewrite the query so the three fields title, year and rating live in a fragment called MovieCard, and the movie id comes from a variable $id (type ID!). The code already passes { id: "m2" }.
Expected: {"movie":{"title":"Spirited Away","year":2001,"rating":8.6}}
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Movie { id: ID!, title: String!, year: Int!, rating: Float }
type Query { movie(id: ID!): Movie }
`);
const movies = [
{ id: 'm1', title: 'Paprika', year: 2006, rating: 7.7 },
{ id: 'm2', title: 'Spirited Away', year: 2001, rating: 8.6 },
];
const rootValue = { movie: ({ id }) => movies.find((m) => m.id === id) };
// TODO: use a variable and a fragment
const query = '{ movie(id: "m1") { title } }';
const result = await graphql({ schema, rootValue, source: query, variableValues: { id: 'm2' } });
console.log(JSON.stringify(result.data ?? result.errors[0].message));{"movie":{"title":"Paprika"}}
Show solution
const query = `
query MoviePage($id: ID!) {
movie(id: $id) { ...MovieCard }
}
fragment MovieCard on Movie { title year rating }
`;3. A computed field
Add a field fullName: String! to Person, computed from firstName and lastName ("Grace Hopper"), and an initials: String! field ("GH"). Use the resolver map: Person.fullName and Person.initials receive the person as their first argument.
Expected: [{"fullName":"Grace Hopper","initials":"GH"},{"fullName":"Alan Turing","initials":"AT"}]
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Person { firstName: String!, lastName: String!, fullName: String!, initials: String! }
type Query { people: [Person!]! }
`);
const people = [
{ firstName: 'Grace', lastName: 'Hopper' },
{ firstName: 'Alan', lastName: 'Turing' },
];
const resolvers = {
Query: { people: () => people },
Person: {
fullName: (person) => 'TODO',
initials: (person) => 'TODO',
},
};
// Attach the resolver map to the schema.
for (const [typeName, fields] of Object.entries(resolvers)) {
for (const [fieldName, resolve] of Object.entries(fields)) {
schema.getType(typeName).getFields()[fieldName].resolve = resolve;
}
}
const result = await graphql({ schema, source: '{ people { fullName initials } }' });
console.log(JSON.stringify(result.data.people));[{"fullName":"TODO","initials":"TODO"},{"fullName":"TODO","initials":"TODO"}]
Show solution
Person: {
fullName: (person) => `${person.firstName} ${person.lastName}`,
initials: (person) => person.firstName[0] + person.lastName[0],
},4. Add a mutation
Implement addBook(input: AddBookInput!): Book!. It must give the new book the next id ("3"), store it in books, and return it. The second query checks that it was stored.
Expected:
{"addBook":{"id":"3","title":"Piranesi","author":"Susanna Clarke"}}
["Circe","Babel","Piranesi"]import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Book { id: ID!, title: String!, author: String! }
input AddBookInput { title: String!, author: String! }
type Query { books: [Book!]! }
type Mutation { addBook(input: AddBookInput!): Book! }
`);
const books = [
{ id: '1', title: 'Circe', author: 'Madeline Miller' },
{ id: '2', title: 'Babel', author: 'R. F. Kuang' },
];
const rootValue = {
books: () => books,
// TODO: implement addBook({ input })
addBook: ({ input }) => ({ id: '0', title: 'TODO', author: 'TODO' }),
};
const add = await graphql({
schema, rootValue,
source: 'mutation Add($input: AddBookInput!) { addBook(input: $input) { id title author } }',
variableValues: { input: { title: 'Piranesi', author: 'Susanna Clarke' } },
});
console.log(JSON.stringify(add.data));
const list = await graphql({ schema, rootValue, source: '{ books { title } }' });
console.log(JSON.stringify(list.data.books.map((b) => b.title)));{"addBook":{"id":"0","title":"TODO","author":"TODO"}}
["Circe","Babel"]
Show solution
addBook: ({ input }) => {
const book = { id: String(books.length + 1), ...input };
books.push(book);
return book;
},5. Enum filter
Add an enum Level { BEGINNER INTERMEDIATE ADVANCED }, change Course.level to use it, and add an optional level: Level argument to courses that filters the list. Then query the advanced courses with an enum literal.
Expected: [{"title":"Compilers","level":"ADVANCED"},{"title":"Distributed Systems","level":"ADVANCED"}]
import { graphql, buildSchema } from 'graphql';
// TODO: add the enum, use it for `level`, add the argument
const schema = buildSchema(`
type Course { title: String!, level: String! }
type Query { courses: [Course!]! }
`);
const courses = [
{ title: 'Intro to Python', level: 'BEGINNER' },
{ title: 'Compilers', level: 'ADVANCED' },
{ title: 'Web APIs', level: 'INTERMEDIATE' },
{ title: 'Distributed Systems', level: 'ADVANCED' },
];
const rootValue = {
courses: ({ level }) => courses, // TODO: filter when level is given
};
const result = await graphql({ schema, rootValue, source: '{ courses { title level } }' });
console.log(JSON.stringify(result.data?.courses ?? result.errors[0].message));[{"title":"Intro to Python","level":"BEGINNER"},{"title":"Compilers","level":"ADVANCED"},{"title":"Web APIs","level":"INTERMEDIATE"},{"title":"Distributed Systems","level":"ADVANCED"}]
Show solution
const schema = buildSchema(`
enum Level { BEGINNER INTERMEDIATE ADVANCED }
type Course { title: String!, level: Level! }
type Query { courses(level: Level): [Course!]! }
`);
const rootValue = {
courses: ({ level }) => (level ? courses.filter((c) => c.level === level) : courses),
};
// query: '{ courses(level: ADVANCED) { title level } }'6. Union search
The schema has union Hit = Artist | Album. Complete the query so each hit prints its __typename and, for artists, name; for albums, title and year.
Expected:
{"__typename":"Artist","name":"Nina Simone"}
{"__typename":"Album","title":"Pastel Blues","year":1965}import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Artist { name: String! }
type Album { title: String!, year: Int! }
union Hit = Artist | Album
type Query { search: [Hit!]! }
`);
const rootValue = {
search: [
{ __typename: 'Artist', name: 'Nina Simone' },
{ __typename: 'Album', title: 'Pastel Blues', year: 1965 },
],
};
// TODO: add inline fragments
const query = '{ search { __typename } }';
const result = await graphql({ schema, rootValue, source: query });
for (const hit of result.data.search) console.log(JSON.stringify(hit));{"__typename":"Artist"}
{"__typename":"Album"}
Show solution
const query = `{
search {
__typename
... on Artist { name }
... on Album { title year }
}
}`;7. Cursor pagination
Implement the items(first, after) resolver so it returns a connection. Cursors are simply the item ids here. The loop then walks through all pages.
Expected:
a,b,c
d,e,f
gimport { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Edge { cursor: String!, node: String! }
type PageInfo { hasNextPage: Boolean!, endCursor: String }
type Connection { edges: [Edge!]!, pageInfo: PageInfo! }
type Query { items(first: Int!, after: String): Connection! }
`);
const all = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const rootValue = {
items: ({ first, after }) => {
// TODO: start after `after`, take `first`, fill in pageInfo
return { edges: [], pageInfo: { hasNextPage: false, endCursor: null } };
},
};
const query = 'query Q($after: String) { items(first: 3, after: $after) { edges { node } pageInfo { hasNextPage endCursor } } }';
let after = null;
let pages = 0;
do {
const { data } = await graphql({ schema, rootValue, source: query, variableValues: { after } });
console.log(data.items.edges.map((e) => e.node).join(',') || '(no items)');
after = data.items.pageInfo.hasNextPage ? data.items.pageInfo.endCursor : null;
} while (after && ++pages < 10);(no items)
Show solution
items: ({ first, after }) => {
const start = after ? all.indexOf(after) + 1 : 0;
const page = all.slice(start, start + first);
return {
edges: page.map((id) => ({ cursor: id, node: id })),
pageInfo: { hasNextPage: start + first < all.length, endCursor: page.at(-1) ?? null },
};
},8. Count the fields
Write countFields(source) that returns how many fields a query selects in total (every Field node, nested ones included, __typename included). Use parse and visit.
Expected: 2, 6 and 4.
import { parse, visit } from 'graphql';
function countFields(source) {
let count = 0;
// TODO: visit the parsed document and count Field nodes
return count;
}
console.log(countFields('{ me { name } }'));
console.log(countFields('{ posts { title author { name avatar } } __typename }'));
console.log(countFields('query { a: user(id: 1) { id } b: user(id: 2) { id } }'));0
0
0
Show solution
function countFields(source) {
let count = 0;
visit(parse(source), {
Field() { count += 1; },
});
return count;
}Test yourself
You need the same field twice with different arguments. What do you use?
- Fragments
- Aliases
- Directives
- Variables
In a resolver map, what is the first argument of Person.fullName?
- The arguments
- The person object (parent)
- The context
- The schema
What should pageInfo.endCursor contain?
- The total count
- The cursor of the last edge on the page
- The first item's id
- The next page number