Thinking in Graphs
A new developer asks, "Which endpoint gives me an author's other books?" In GraphQL that question has no answer, because there are no such endpoints. There is one graph of connected types, and you walk it.
The rule
Types are nodes, fields are edges; a query is a walk.
Model the bookshop as things and the links between them:
type Book {
id: ID!
title: String!
author: Author!
reviews: [Review!]!
}
type Author {
id: ID!
name: String!
books: [Book!]!
}
type Review {
id: ID!
rating: Int!
book: Book!
}- Each object type (
Book,Author,Review) is a kind of node. - A field that returns another object type (
author,books,reviews) is an edge: a link you can follow. - A field that returns a plain value (
title,rating) is a leaf: where a walk stops.
Every walk starts at an entry point on the Query type, such as book(id:). From there you follow edges as far as you need:
query {
book(id: "b1") {
author {
books { title }
}
}
}This answers "other books by the author of b1" without anyone designing an endpoint for it. Links run both ways when useful (Book.author and Author.books), so a client can start from either side.
Design the graph around your domain, the way people talk about the business, not around your database tables. A Review has a book, not a book_id column; the server works out how to join.
The shortcut
To write a query from a question, say the path out loud, then nest it. Each "'s" in the sentence becomes one level of braces.
Find the entry point
Start at
Query.book(id: "b1").
The usual mistake is designing fields like authorId: ID! and making the client look the author up in a second request. Expose the edge author: Author! instead.
Drills
Answer fast — trust the rule.
In the bookshop graph, which field is an edge to another node?
Where does every query walk begin?
Which query lists the titles of all books by the author of book b1?
A teammate proposes Review.bookId: ID! as the only link from a review to its book. What is better graph design?
Remember
- Types are nodes, fields are edges; a query is a walk from a
Queryentry point. - Say the path out loud, then nest one level per step, ending at leaves.
- Trap: exposing raw IDs instead of edges, and modelling tables instead of the domain.
