A restaurant menu that has been printed and handed to regulars can't be changed on a whim. Rename a dish and the kitchen no longer recognises old orders. It's safer to add the new dish, mark the old one "being replaced", and remove it once nobody orders it any more.
A GraphQL schema is the same. It's a contract between the server and all of its clients, and the Bookshop has three: the shop website, the cashier app and the admin dashboard. The three can't be updated at the same moment. Good schema design lets the schema grow without breaking the clients that already exist.
Naming
| Part | Style | Example in the Bookshop |
|---|---|---|
| Type, input, enum, union | PascalCase, a noun | Book, CoverUpload, StockStatus |
| Field and argument | camelCase | coverUrl, priceCents, bookId |
| Enum value | SCREAMING_SNAKE_CASE | IN_STOCK, SOLD_OUT |
| Mutation | the verb first, then the noun | createBook, updateStock, attachCover |
| Input and payload | mutation name + Input / Payload |
RestockBookInput, RestockBookPayload |
A mutation that starts with a verb says straight away what happens. A type name carries no verb (Book, not GetBookResponse), because the same type serves many operations.
An input type and a payload type per mutation
updateStock(id: ID!, stock: Int!): Book is easy to write, but hard to grow. The shape many large APIs use:
type Mutation {
restockBook(input: RestockBookInput!): RestockBookPayload!
}
input RestockBookInput {
bookId: ID!
stock: Int!
}
type RestockBookPayload {
book: Book
userErrors: [UserError!]!
}
type UserError {
field: [String!]
message: String!
}
- An input type groups related arguments into one object. The client sends just one
$inputvariable, and an input type can be reused, such as anAddressInputinside several other inputs. Adding an optional field to the input later doesn't break old clients. - Each mutation gets its own input, even when the contents look alike, so each can change without disturbing the other.
- A payload type wraps the result. Today it holds
bookanduserErrors; tomorrow it can gain another field without changing the mutation's return type.userErrorscarries input mistakes as data, like theStockErrorunion in the "Error Handling in GraphQL" lesson.
Nullability: where ! is safe
A ! is a promise: the value is always there. If that promise fails even once, its null climbs to the nearest place that may be null (the "Schema & Type System" lesson).
- Safe as non-null: values that really are always there and come from the same place, such as
id,title,price, and lists from your own database ([Book!]!). - Better nullable: fields an access rule may refuse (
stockin the "Authentication & Authorization" lesson), fields computed by another service, or fields that can fail on their own. In large schemas most fields are nullable, so one failure removes one field, not the whole response. - The direction of a change decides whether it's safe. For output: nullable to non-null is safe, non-null to nullable is dangerous (clients already assume it's always there). For arguments and inputs: required to optional is safe, optional to required breaks clients.
Deprecation, not a new version
GraphQL needs no /v2. You add the new field, mark the old one @deprecated with a reason, and remove it once nobody uses it any more:
type Book {
price: Int! @deprecated(reason: "Use priceCents.")
priceCents: Int!
}
Old clients keep working: { books { title price status } } is still answered in full. Tools such as GraphiQL and linters warn about it; graphql-js's NoDeprecatedCustomRule writes it like this: The field Book.price is deprecated. Use priceCents.
Now guess: the team renames price to priceCents outright, with no deprecation. The shop website, not yet updated, still sends { books { title price status } }. What comes back: price as null, or something worse?
Renaming outright is very different. Once price becomes priceCents, the shop website's query fails validation: Cannot query field "price" on type "Book". The whole operation is refused, so even the title and status don't arrive. The same happens if updateStock(id, stock) is changed to updateStock(input:) in one go: the cashier app gets Unknown argument "id" on field "Mutation.updateStock". The way to do it: add restockBook(input:) beside it, deprecate updateStock, then watch each field's usage drop to zero before removing it.
Enums, not strings
status: StockStatus! beats status: String!. An enum lists the possible values in the schema, and a wrong value is refused before any resolver runs (Value "EMPTY" does not exist in "StockStatus" enum.). Turning the enum into a String later breaks clients that write books(status: SOLD_OUT): String cannot represent a non string value: SOLD_OUT. Adding a new enum value needs care too, because a client with a switch may meet a value it doesn't know yet.
The Node interface and global IDs
Relay, the GraphQL client from Meta, uses the global object identification pattern: every object can be fetched again through one node field.
interface Node {
id: ID!
}
type Book implements Node {
id: ID!
title: String!
}
type Query {
node(id: ID!): Node
}
- An interface is a set of fields every type that
implementsit must have. The difference from a union (SearchResult = Book | Authorin the "Variables & Fragments" lesson): a union has no shared fields, an interface does. - A global ID is unique across the whole schema, not just within one table. Usually the type name and the local id are base64-encoded:
btoa("Book:1")gives"Qm9vazox". A client cache can store any object by its id alone. { node(id: "Qm9vazox") { ... on Book { title } } }answers The Rainbow Troops.
The mini GraphQL engine in the Lab doesn't run interfaces yet, so this part is only written as SDL.
Schema-first or code-first
- Schema-first: the SDL is written first (a
.graphqlfile), then the resolvers follow it. Like this whole track. The schema is easy for a team to read and discuss, but you have to keep the resolvers matching the SDL. In TypeScript, the server preset of GraphQL Code Generator helps with that (@eddeee888/gcg-typescript-resolver-files, run withnpx graphql-codegen). It creates the resolver files and their types from the SDL, and a resolver that is not written yet becomes a TypeScript error. - Code-first: the schema is defined in code, with Pothos, TypeGraphQL or Nexus for example, and the SDL is generated. Its main advantage: the schema and the implementation are always in sync, and TypeScript type safety is easier; with Pothos or TypeGraphQL the types flow from the model to the resolvers with no extra generation step (Nexus has a typegen step of its own). For a new project, Pothos is the most actively maintained: the last stable Nexus version, 1.3.0, came out in March 2022, and TypeGraphQL 2 is still a release candidate (
2.0.0-rc.3).
⚠️ Schema decisions that break clients later
- Renaming or removing a field outright. Old clients' queries are refused whole. Add the new one,
@deprecatedthe old. - Every field non-null. One field that fails wipes out the whole object above it, even the whole
data. - Many loose arguments on a mutation. Adding a required argument breaks clients. Start with one
input. - A status as a free string. Typos aren't caught, and the possible values aren't documented. Use an enum.
TL;DR: A schema is a contract with clients that aren't updated together. Types in PascalCase, fields in camelCase, enum values in SCREAMING_SNAKE_CASE, mutations starting with a verb. Each mutation uses its own input type (groups arguments, can be reused, safe to extend) and a payload type (say book plus userErrors). ! only for values that are certainly always there; in large schemas most fields are nullable. Don't make a new version: add the field, put @deprecated(reason:) on the old one, remove it once its usage is zero; renaming outright gets old queries refused (Cannot query field "price" on type "Book".). Use enums, not strings. A Node interface with global IDs (btoa("Book:1")) lets any object be fetched through node(id:). A union picks one of several object types, an interface shares fields. Schema-first writes the SDL first; code-first generates the SDL from code, so it is always in sync with the implementation.
⚡ An input and a payload for each mutation
Write:
type Mutation {
restockBook(input: RestockBookInput!): RestockBookPayload!
}
input RestockBookInput {
bookId: ID!
stock: Int!
}
Meaning: An input type groups related arguments into one object, and it's easy to reuse. The client sends just one $input variable, and an optional field can be added later without breaking old clients.
⚡ Deprecation, not a new version
Write:
type Book {
price: Int! @deprecated(reason: "Use priceCents.")
priceCents: Int!
}
Guess first: the team renames price to priceCents outright, with no deprecation. The shop website still asks for price. What happens?
Its whole query fails validation: Cannot query field "price" on type "Book". Not even the title and status arrive.
Meaning: Add the new field, mark the old one @deprecated, then remove it once nobody uses it any more.
⚡ An exclamation mark is a promise
Meaning: Use ! for values that really are always there, like id and title. Fields an access rule may refuse, or that come from another service, are better nullable, so one failure removes one field, not the whole response.