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.