Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Practice and Review

Practice Exercises with Solutions

15 graded GraphQL exercises: write and fix queries, repair schemas, design a mutation, find the N+1, add pagination and spot nullability bugs.

Reading about GraphQL is one thing; writing it is another. These 15 exercises go from easy to hard and touch every chapter of the tutorial. Each one has a runnable editor with a starter that prints TODO or FAIL, a clear goal, and a hidden solution you can open after you have tried.

How it works:

  • Edit only the part between // ---- your code ---- and // ---- end ----, then press Run. The checks below that part tell you whether you got it.
  • No real GraphQL server runs on this site. Where an exercise needs to run a query, a tiny stand-in executor (the run function) does it. It supports fields, nested selections and arguments, and nothing else.
  • A solution shows only the code that replaces your part.

Three levels

Easy (1-5) Queries, schema reading, nullability.
Medium (6-11) Mutations, resolvers, N+1, pagination.
Hard (12-15) Directives, limits, evolution, errors.

Stuck? Reread the linked lesson, then peek at the solution.

1 / 2

Exercise 1 (easy): Write a query

Request the title and the author's name of every book whose genre is FICTION. Related lesson: Fields, Arguments and Nested Selections.

JS Exercise 1: write the query

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
const query = `{ books(genre: FICTION) { title author { name } } }`;

The genre argument filters on the server, and the selection set asks for exactly two things per book. author is an object field, so it needs its own braces.

Exercise 2 (easy): Fix the broken query

This query fails validation. Fix it so that it returns each book's title and the author's name. Related lesson: How Execution Works and How Errors Behave.

JS Exercise 2: fix the query

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
const query = `{ books { title author { name } } }`;

The schema calls the relationship author, not writer. A real server would answer with a validation error and no data at all; the error message names the field and the type.

Exercise 3 (easy): Predict the response

Without running it, write down what { book(id: "2") { title author { name } } } returns in data. Set expected to that object, then run to check. Related lesson: Your First Query.

JS Exercise 3: predict the shape

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
const expected = { book: { title: "Stars", author: { name: "Tomas" } } };

The response mirrors the query: a book key (the field name, since there is no alias), containing only title and author, which contains only name. The id and genre fields were not requested, so they are absent.

Exercise 4 (easy): Repair the schema's nullability

The SDL below has three problems. A book looked up by an unknown id is a normal situation, the list of books should always exist and never contain null, and every book must have an id and title. Edit the schema. Related lesson: Lists and Non-Null Types.

JS Exercise 4: fix the nullability

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
const sdl = `type Query {
  book(id: ID!): Book
  books: [Book!]!
}

type Book {
  id: ID!
  title: String!
}`;

A non-null book would turn "not found" into an error that wipes out data. The list is non-null with non-null items, so clients never have to guard against null items.

Exercise 5 (easy): Where does the null land?

When a non-null field fails, null bubbles up to the nearest nullable parent. The landing function below computes that for a chain of levels (from the failing field upward). Predict the answers for the two scenarios. Related lesson: How Execution Works and How Errors Behave.

JS Exercise 5: null bubbling

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
const answerA = "posts[1]";
const answerB = "data";

In A, author is non-null so the null moves up one level to the list item, which is nullable: only that item becomes null. In B, every level up to data forbids null, so the whole data is null.

Exercise 6 (medium): Design a mutation

Write the SDL for a mutation addComment that takes ONE input object (postId: ID! and text: String!) and returns a payload with a nullable comment and a non-null list userErrors. Name the types AddCommentInput and AddCommentPayload. Related lessons: Schema Design Best Practices and Modeling Errors.

JS Exercise 6: design the mutation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
const sdl = `input AddCommentInput {
  postId: ID!
  text: String!
}

type AddCommentPayload {
  comment: Comment
  userErrors: [UserError!]!
}

type Mutation {
  addComment(input: AddCommentInput!): AddCommentPayload!
}`;

The payload type leaves room to add fields later. comment is nullable because validation can fail, and userErrors is always present so clients can check its length without a null test.

Exercise 7 (medium): Implement the mutation resolver

Implement addComment({ postId, text }). It must return { comment, userErrors }. Rules: an unknown post gives code NOT_FOUND, a blank text gives BLANK, text longer than 50 characters gives TOO_LONG; in all failure cases comment is null. On success, comment has an id (use nextId++), postId and the trimmed text. Related lesson: Mutations and Subscriptions.

JS Exercise 7: the resolver

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function addComment({ postId, text }) {
  const fail = (field, message, code) => ({ comment: null, userErrors: [{ field, message, code }] });
  if (!posts.has(postId)) return fail("postId", "Post not found.", "NOT_FOUND");
  const clean = String(text ?? "").trim();
  if (clean.length === 0) return fail("text", "Text cannot be blank.", "BLANK");
  if (clean.length > 50) return fail("text", "Text is too long.", "TOO_LONG");
  return { comment: { id: String(nextId++), postId, text: clean }, userErrors: [] };
}

Expected failures are returned as data in userErrors, not thrown.

Exercise 8 (medium): Find the N+1

The resolvers below fetch a post's author and comments separately, once per post. The simulation counts the database queries for { posts { author { name } comments { text } } } over 4 posts. Guess the number first. Related lesson: The N+1 Problem and DataLoader.

JS Exercise 8: count the queries

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
const guess = 9;

One query for the list, plus one author query and one comments query for each of the 4 posts: 1 + 4 + 4 = 9. With batching the same page needs 3 (posts, authors, comments), no matter how many posts there are.

Exercise 9 (medium): Write the batch function

A DataLoader calls your batch function once with all the keys. Implement batchAuthors(ids) so it makes ONE lookup (findAuthors) and returns the authors in the order of ids, with null for ids that do not exist. Related lesson: The N+1 Problem and DataLoader.

JS Exercise 9: batch function

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function batchAuthors(ids) {
  const found = findAuthors(ids);
  const byId = new Map(found.map((a) => [a.id, a]));
  return ids.map((id) => byId.get(id) ?? null);
}

A Map makes the reordering linear. Databases return rows in whatever order they like, and a loader hands results to callers by position, so this step is essential.

Exercise 10 (medium): Add cursor pagination

Implement paginate(items, { first, after }). The cursor of an item is its id as a string. Return { edges: [{ cursor, node }], pageInfo: { hasNextPage, endCursor } }, starting after the item whose id equals after (or at the start if there is no after). Related lesson: Pagination: Offset, Cursor and Connections.

JS Exercise 10: pagination

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function paginate(items, { first, after }) {
  const start = after === undefined ? 0 : items.findIndex((i) => String(i.id) === after) + 1;
  const slice = items.slice(start, start + first + 1);
  const edges = slice.slice(0, first).map((node) => ({ cursor: String(node.id), node }));
  return {
    edges,
    pageInfo: {
      hasNextPage: slice.length > first,
      endCursor: edges.length ? edges[edges.length - 1].cursor : null,
    },
  };
}

Fetching one extra item reveals whether a next page exists without a count query. A production API would also cap first and make the cursor opaque.

Exercise 11 (medium): A resolver that uses context

Make Query.me return the logged-in user from the context. If there is no user in the context, throw an ExpectedError with code UNAUTHENTICATED. Related lesson: Resolvers.

JS Exercise 11: me needs a login

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
const resolvers = {
  Query: {
    me: (parent, args, context) => {
      if (!context.user) throw new ExpectedError("Login required.", "UNAUTHENTICATED");
      return context.user;
    },
  },
};

The context is built once per request (after authentication) and handed to every resolver as the third argument.

Exercise 12 (hard): Evaluate @skip and @include

A field with directives is included when no @skip evaluates to true and every @include evaluates to true. A directive argument if is either a boolean or a variable name such as "$hide" whose value is in variables. Implement shouldInclude(directives, variables). Related lesson: Variables and Directives.

JS Exercise 12: directives

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function shouldInclude(directives, variables) {
  const value = (arg) => (typeof arg === "string" && arg.startsWith("$") ? variables[arg.slice(1)] : arg);
  for (const d of directives) {
    if (d.name === "skip" && value(d.args.if) === true) return false;
    if (d.name === "include" && value(d.args.if) !== true) return false;
  }
  return true;
}

Exercise 13 (hard): Measure query depth

A selection is a nested object: { posts: { author: { name: true } } }, where true marks a leaf field. Implement depth(selection), which returns how many levels of fields the query has (this example is 3, a lone { name: true } is 1). A depth limit built on this stops abusive nesting before execution. Related lesson: Query Depth, Complexity and Other Attacks.

JS Exercise 13: depth

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function depth(selection) {
  let deepest = 0;
  for (const child of Object.values(selection)) {
    const d = child === true ? 1 : 1 + depth(child);
    deepest = Math.max(deepest, d);
  }
  return deepest;
}

Each object field adds one level on top of its deepest child.

Exercise 14 (hard): Classify schema changes

Implement classify(change) returning "BREAKING", "RISKY" or "SAFE". Rules: removing a type, field or enum value, changing a field's type, making an output field nullable, and adding a required input field are breaking; adding an enum value is risky; everything else (new type, new field, new optional input) is safe. Related lesson: Schema Evolution, Federation and Tooling.

JS Exercise 14: classify changes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function classify(change) {
  const breaking = new Set([
    "TYPE_REMOVED", "FIELD_REMOVED", "ENUM_VALUE_REMOVED", "FIELD_TYPE_CHANGED",
    "OUTPUT_FIELD_BECAME_NULLABLE", "REQUIRED_INPUT_FIELD_ADDED",
  ]);
  if (breaking.has(change.kind)) return "BREAKING";
  if (change.kind === "ENUM_VALUE_ADDED") return "RISKY";
  return "SAFE";
}

Exercise 15 (hard): Format errors safely

Implement formatError(error). For an ExpectedError, return { message, extensions: { code } }. For any other error, return { message: "Internal server error", extensions: { code: "INTERNAL" } } and push the real message into serverLog, so secrets never reach the client. Related lessons: Modeling Errors and Project: A Secured API Layer.

JS Exercise 15: error formatter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function formatError(error) {
  if (error instanceof ExpectedError) {
    return { message: error.message, extensions: { code: error.code } };
  }
  serverLog.push(error.message);
  return { message: "Internal server error", extensions: { code: "INTERNAL" } };
}

Real servers also attach a request id to the masked error so a support request can be matched to the log line.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. An exercise says a field must exist but may be missing for normal reasons, such as an unknown id. How should its type be declared?

    Nullable types let an expected absence stay local instead of turning into an error that bubbles up.
  2. 2. A page of 20 items with their authors and comments takes 41 queries. What is the likely cause?

    1 + 20 + 20 = 41 is the N+1 pattern. Batching reduces it to a handful of queries.
  3. 3. Why does a batch function return values in the order of the keys?

    Results are matched to callers by position, so rows must be reordered and gaps filled with null.

Summary

  • You have written and fixed queries, schemas, mutations, resolvers and loaders.
  • Nullability decides how far an error spreads; choose it per field.
  • Batching and cursors are the two fixes every list-heavy API needs.
  • Depth limits, change classification and error masking are small functions with big effects.

Next: GraphQL Interview Questions.