はじめに
基本のクエリ
GraphQL ではクライアントが必要なデータを正確に指定できます。クエリでデータを取得し、レスポンスはクエリの形をそのまま反映します。REST API でよくある過剰取得(over-fetching)や取得不足(under-fetching)を回避できます。
# Query - read data
query {
user(id: 1) {
id
name
email
posts {
title
content
}
}
}
# Response
{
"data": {
"user": {
"id": 1,
"name": "Alice",
"email": "[email protected]",
"posts": [
{ "title": "Hello", "content": "World" }
]
}
}
}変数付きクエリ
変数はクエリをパラメータ化し、同じ操作を入力を変えて再利用できるようにします。操作ヘッダーで $name: Type と宣言します。クエリ文字列は静的なままで、呼び出しごとに変わるのは変数の JSON だけです。
# Declare variables with operation name
query GetUser($id: ID!, $withPosts: Boolean!) {
user(id: $id) {
name
posts @include(if: $withPosts) {
title
}
}
}
# Variables sent alongside the query
{
"id": "1",
"withPosts": true
}ミューテーションの基本
ミューテーションはデータを変更し、クエリと同様に選択セット を返します。慣例として、変更後のデータを読み出すフィールドを続けるべきです。GraphQL はミューテーションを直列に(1 つずつ)実行し、クエリのフィールドは並列に実行します。
# Mutation - write data, then return the result
mutation {
createUser(input: { name: "Bob", email: "[email protected]" }) {
id
name
}
}
# Response
{
"data": {
"createUser": {
"id": "42",
"name": "Bob"
}
}
}フィールドと選択セット
選択セットは波括弧の中のフィールドのリストです。スカラーと enum はリーフ値を返し、オブジェクト型はネストした選択セットを必要とします。オブジェクト型へのサブセレクションの書き忘れは、よくあるバリデーションエラーです。
# You must select fields - GraphQL never returns whole objects
query {
user(id: 1) {
# this block is a "selection set"
name
email
}
}
# Selecting a scalar returns its value directly
# Selecting an object REQUIRES a sub-selection set
query {
user(id: 1) {
name # scalar - OK
posts { # object - needs { ... }
title
}
}
}GraphQL と REST の比較
REST は固定された形のエンドポイントを多数公開します。GraphQL は 1 つのエンドポイントで、形をクライアントが定義します。ラウンドトリップが減り、過剰/不足取得も防げます。代償としてサーバーが複雑になり、キャッシュは POST 経由になります。
# REST: multiple round trips, fixed shapes
GET /users/1 -> { id, name, email, address, ... }
GET /users/1/posts -> [ { id, title, body, author, ... } ]
# GraphQL: one request, client-defined shape
query {
user(id: 1) {
name
posts { title }
}
}
# One endpoint, one POST request
POST /graphql
{ "query": "...", "variables": { ... } }イントロスペクション
イントロスペクションはクライアントが実行時にスキーマを発見できる仕組みです。GraphiQL、Apollo Studio、コードジェネレーターなどのツールがこれに依存しています。ルートフィールド __schema と __type が入り口です。本番サーバーでは内部構造を隠すために無効化することもあります。
# Ask the schema what types and fields it has
{
__schema {
types {
name
kind
}
}
}
# Inspect a specific type's fields
{
__type(name: "User") {
name
fields {
name
type { name kind ofType { name kind } }
}
}
}スキーマと型システム
スキーマの宣言
schema ブロックはルートの操作型を結び付けます。ルート型が Query、Mutation、Subscription という名前なら、Apollo/GraphQL.js が自動的に推論するため、この宣言は完全に省略できます。
# SDL - Schema Definition Language
schema {
query: Query
mutation: Mutation
subscription: Subscription
}
# In most servers the schema is inferred from the
# Query/Mutation/Subscription types, so this block is optional.ルート型
Query、Mutation、Subscription がスキーマの入り口です。必須のルート型は Query だけです。各ルートフィールドがクライアントが実行できる操作になります。ミューテーションは動詞(createUser)、クエリは名詞とするのが慣例です。
type Query {
user(id: ID!): User
users(limit: Int = 10): [User!]!
}
type Mutation {
createUser(input: CreateUserInput!): User!
}
type Subscription {
postAdded: Post!
}型定義
型は type キーワードの後にフィールドを並べて定義します。各フィールドには名前と戻り値の型があります。! 接尾辞は非 null を意味し、[Type!] は非 null 要素のリスト、[Type!]! は非 null 要素の非 null リストです。
# Object type - the most common building block
type User {
id: ID!
name: String!
age: Int
email: String
posts: [Post!]!
}
type Post {
id: ID!
title: String!
author: User!
}説明の追加
トリプルクォートの文字列(定義の直前の 1 行文字列も可)は説明としてスキーマの一部になります。GraphiQL のドキュメントやイントロスペクションに表示されます。# の通常コメントは開発専用で取り除かれるので、ユーザー向けの文書にはトリプルクォートを使いましょう。
"""A registered user of the platform."""
type User {
"""The unique, immutable identifier."""
id: ID!
"Display name shown publicly."
name: String!
# plain # comments are NOT exposed to clients
email: String
}拡張を使ったスキーマ
extend type は別の場所で宣言された型にフィールドを追加します。大きなスキーマをファイルに分割したり、モジュール固有のフィールドを追加したりする方法です。型の宣言は 1 回で、拡張は何度もできますが、各フィールドは 1 回しか定義できません。
# Extend an existing type without redefining it
type User {
id: ID!
name: String!
}
extend type User {
age: Int
posts: [Post!]!
}
# Useful for splitting a schema across files,
# or for adding fields only in certain modules.スキーマファーストとコードファースト
スキーマファーストは SDL を手で書き、リゾルバを結び付けます(Apollo の古典的アプローチ)。コードファーストは TypeScript のデコレーター/ビルダー(Nexus、TypeGraphQL、Pothos)でスキーマをプログラム的に構築し、スキーマとリゾルバの間の型安全性が得られます。どちらも同じ実行時スキーマを生み出します。
# 1) Schema-first: write SDL, bind resolvers
const typeDefs = `
type Query { hello: String }
`;
const resolvers = { Query: { hello: () => "world" } };
const server = new ApolloServer({ typeDefs, resolvers });
# 2) Code-first: build with builders (Nexus, TypeGraphQL)
export const Query = queryType({
definition(t) {
t.string("hello", { resolve: () => "world" });
},
});スカラー型
組み込みスカラー
GraphQL には 5 つの組み込みスカラーがあります: Int、Float、String、Boolean、ID。ID は文字列としてシリアライズされますが、意味的には識別子であり、クライアントは不透明なものとして扱うべきです。組み込みの Date や DateTime はないので、自分で定義します。
type Example {
id: ID! # unique identifier, serialized as string
name: String! # UTF-8 text
age: Int # 32-bit integer
score: Float # double-precision float
active: Boolean! # true / false
}カスタムスカラー
カスタムスカラーはドメインのプリミティブを表現できます。宣言したら、シリアライズ(JSON へ)、パース(変数から)、リテラルパース(インライン AST から、任意)を行うリゾルバを用意する必要があります。なければ値はそのまま素通りします。
# Declare a custom scalar in SDL
scalar DateTime
scalar URL
scalar JSON
type Event {
id: ID!
at: DateTime!
link: URL
metadata: JSON
}スカラーのリゾルバ
スカラーのリゾルバには 3 つの任意メソッドがあります。serialize は内部値を JSON 出力へ変換し、parseValue は変数の入力を内部形式へ、parseLiteral はクエリ AST のインラインリテラルを内部形式へ変換します。完全に型付けされたスカラーには 3 つすべてを定義しましょう。
const resolvers = {
DateTime: {
// value -> JSON sent to client
serialize: (value: Date) => value.toISOString(),
// variable value -> internal value
parseValue: (value: string) => new Date(value),
// inline AST literal -> internal value
parseLiteral: (ast) => {
if (ast.kind === "StringValue") {
return new Date(ast.value);
}
return null;
},
},
};Date/DateTime スカラー
graphql-scalars パッケージは実績のあるスカラーを提供します: DateTime、Date、Time、EmailAddress、URL、UUID、BigInt、JSON など。手作りよりこちらが推奨です。特にエッジケースの多い ISO 8601 の日付パースでは顕著です。
# Use graphql-scalars for well-tested common types
import { DateTimeResolver } from "graphql-scalars";
const resolvers = {
DateTime: DateTimeResolver,
Date: DateResolver,
Time: TimeResolver,
};
# In SDL
scalar DateTime
type Query {
now: DateTime!
}JSON スカラー
JSON スカラーは任意のデータを素通しさせるので、動的な設定やメタデータに便利です。代償として、型安全性とフィールド単位のバリデーションが失われ、クライアントはサブフィールドを選択できません。控えめに使いましょう。型付きのオブジェクト型のほうがほぼ常に良い選択です。
scalar JSON
type Query {
# accept arbitrary JSON as input or output
config: JSON
setConfig(value: JSON): JSON
}
# The simplest pass-through resolver
const resolvers = {
JSON: {
serialize: (v) => v,
parseValue: (v) => v,
parseLiteral: (ast) => parseJsonLiteral(ast),
},
};オブジェクト型
オブジェクト型の定義
オブジェクト型は名前付きフィールドと戻り値の型の集まりです。オブジェクト型がお互いを参照してグラフを作ります(User は Posts を持ち、Post は Author を持つ)。オブジェクト型は出力型であり、入力には input 型を使います。
type User {
id: ID!
name: String!
email: String
createdAt: String!
}
type Post {
id: ID!
title: String!
body: String!
published: Boolean!
}フィールドとフィールド型
すべてのフィールドは戻り値の型を宣言します。デフォルトは null 許容で、! で非 null になります。リストは [] で包みます。! の位置が重要です: [String] は null 許容で null 要素を含められ、[String!] は null 許容だが要素は非 null、[String!]! は null も null 要素も許しません。
type Product {
id: ID! # non-null ID
name: String! # non-null string
price: Float! # non-null float
discount: Float # nullable float
tags: [String!]! # non-null list of non-null strings
reviews: [Review] # nullable list of nullable reviews
}非 null とリスト
! の配置が各レベルの null 許容性を制御します。非 null は強力ですが危険でもあります。非 null のフィールドでリゾルバが null を返すと、エラーが伝播して親のフィールドも null になります。デフォルトは null 許容にし、値が本当に保証できる場所だけ非 null にしましょう。
type Example {
a: [String] # may be null; items may be null
b: [String!] # may be null; items NOT null
c: [String]! # NOT null; items may be null
d: [String!]! # NOT null; items NOT null
name: String # may be null
name2: String! # NOT null - errors if null returned
}ネストしたオブジェクト
オブジェクト型がお互いを参照してグラフを作るので、リレーションをたどるクエリが可能です(user -> posts -> author -> profile)。型間の循環参照は問題なく、よくあります。このグラフこそが、GraphQL をエンドポイントの木ではなくグラフにしているものです。
type User {
id: ID!
name: String!
profile: Profile!
posts: [Post!]!
}
type Profile {
bio: String
avatar: String
}
type Post {
id: ID!
title: String!
author: User! # back-reference creates the graph
}オブジェクトのフィールド引数
引数はルートフィールドだけでなく、任意のフィールドに付けられます。これにより 1 つの型が、関連データのフィルタ/ページネーション付きビューを公開できます(例: user.posts(limit: 10))。デフォルト値のある引数はクエリでは省略可能になります。
type User {
id: ID!
name: String!
# an object field can take arguments
posts(limit: Int = 5, after: ID): [Post!]!
role(type: RoleType!): Role
}
type Query {
user(id: ID!): User
}クエリ
Query 型
Query 型はすべての読み取りの入り口です。ここにある各フィールドがクライアントが要求できるトップレベルの操作になります。読み取り専用に絞り、書き込みは Mutation に置きましょう。フィールド名は名詞(users、user、search)が慣例です。
type Query {
me: User!
user(id: ID!): User
users(limit: Int = 20, offset: Int = 0): [User!]!
search(term: String!): [SearchResult!]!
}
# Clients run these as operations:
# query { me { name } }
# query { user(id: "1") { name } }複数のフィールド
1 つのクエリは複数 のルートフィールドを選択できます。GraphQL はそれらを並列実行します(ミューテーションを除く)。関連する取得が 1 回のラウンドトリップにまとまり、REST に対する大きな効率面の利点です。
# Several fields in one request - executed in parallel
query {
me { name email }
user(id: "1") { name }
users(limit: 3) { id name }
}
# Response contains all three under "data"
{
"data": {
"me": { "name": "Alice", "email": "[email protected]" },
"user": { "name": "Bob" },
"users": [ { "id": "1", "name": "Bob" }, ... ]
}
}エイリアス
エイリアスはレスポンス内のフィールド名を変更します。同じフィールドを異なる引数で選択するときには必須です。JSON オブジェクトのキーは一意でなければならないからです。短い、あるいはより意味の分かりやすいレスポンスキーにも便利です。
# Same field twice with different args needs aliases
query {
alice: user(id: "1") { name }
bob: user(id: "2") { name }
}
# Response keys match the aliases
{
"data": {
"alice": { "name": "Alice" },
"bob": { "name": "Bob" }
}
}ネストしたクエリ
リレーションをたどれることが GraphQL の超能力です。クライアントは 1 つのクエリでグラフを歩けます(user -> posts -> comments -> author)。サーバーは各フィールドをリゾルバで解決します。深いネストは問題ありませんが、バックエンドの N+1 クエリには注意しましょう。
query {
user(id: "1") {
name
posts { # traverse relationship
title
comments { # and another level
author {
name
}
}
}
}
}引数付きクエリ
引数はインラインリテラルか変数です。静的な値にはインラインリテラルで十分です。ユーザー入力や呼び出しごとに変わる値には変数を使いましょう。変数ならクエリをキャッシュ可能に保て、文字列連結も避けられます。
# Schema
type Query {
user(id: ID!, includeEmail: Boolean = false): User
}
# Inline arguments
query {
user(id: "1", includeEmail: true) {
name
email
}
}
# Prefer variables for dynamic values
query($uid: ID!, $withEmail: Boolean!) {
user(id: $uid, includeEmail: $withEmail) {
name
email
}
}操作名(Operation Name)
操作に名前を付ける(query GetUserProfile)のは任意ですが、強く推奨されます。名前付き操作はデ バッグしやすく、ログや Apollo Studio に現れます。1 つのドキュメントで複数の操作を送るときや、永続化クエリでは必須です。
# Give operations a name - required in production
query GetUserProfile($id: ID!) {
user(id: $id) {
id
name
email
}
}
mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) {
id
}
}ミューテーション
Mutation 型
Mutation 型は書き込みの入り口です。慣例として、ミューテーションのフィールド名は動詞にします(createUser、updatePost)。ミューテーションは書かれた順に直列実行されるため、1 つのリクエスト内の複数のミューテーションフィールドでも、順序に依存する副作用が安全に行えます。
type Mutation {
createUser(input: CreateUserInput!): User!
updateUser(id: ID!, input: UpdateUserInput!): User!
deleteUser(id: ID!): Boolean!
createPost(input: CreatePostInput!): Post!
}
# Client mutation
mutation {
createUser(input: { name: "Alice", email: "[email protected]" }) {
id
name
}
}Input を使うミューテーション
ミューテーションの引数には input 型を使いましょう。関連するフィールドをまとめられ、シグネチャがきれいになり、安全に進化します(任意のフィールドを壊さずに追加できる)。ミューテーションのペイロードは必ず変数で渡し、インラインリテラルは使わないようにしましょう。
input CreateUserInput {
name: String!
email: String!
age: Int
}
type Mutation {
createUser(input: CreateUserInput!): User!
}
mutation($input: CreateUserInput!) {
createUser(input: $input) {
id
name
}
}
# { "input": { "name": "Bob", "email": "[email protected]" } }ペイロードの返却
よくあるパターンは、結果を errors、成功フラグ、クライアントのミューテーション ID などと一緒に包むペイロードオブジェクトです。例外を投げるより柔軟で、部分的な成功や構造化されたバリデーションエラーを、エンティティと一緒に返せます。
# Return the changed entity AND related fields like errors
type CreateUserPayload {
user: User
errors: [UserError!]!
}
type UserError {
field: String
message: String!
}
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
}複数のミューテーション
クエリ(並列)と違い、1 つの操 作内のミューテーションは宣言順に直列実行されます。2 つ目のミューテーションが 1 つ目の効果を見ることが保証されます。あるミューテーションフィールドがエラーになっても、後のものは実行されるので、入力のバリデーションと必要に応じたトランザクションを使いましょう。
# Multiple mutations run SERIALLY in declared order
mutation {
createPost(input: { title: "A" }) {
id
}
publishPost(id: "1") {
publishedAt
}
}冪等性
ネットワークの再試行で書き込みが重複することがあります。冪等性キーがあれば、サーバーが再試行を認識して重複を作らず元の結果を返せます。決済、注文、取り消せない操作には不可欠です。
# Use a client mutation id or idempotency key
input CreateOrderInput {
idempotencyKey: String!
productId: ID!
quantity: Int!
}
type Mutation {
createOrder(input: CreateOrderInput!): Order!
}
# Clients retry with the SAME idempotencyKey on failure
# Server returns the original order instead of creating a duplicateサブスクリプション
Subscription 型
サブスクリプションはイベント発生時にサーバーからクライアントへデータを push します。通常は WebSocket 経由です。長期間持続する操作です。ペイロードは小さく保ちましょう。詳細データは通常、大きなオブジェクトをストリーミングせず、後続のクエリで取得します。
type Subscription {
postAdded: Post!
userJoined(roomId: ID!): User!
messageReceived(userId: ID!): Message!
}
# Client subscribes (usually over WebSocket)
subscription {
postAdded {
id
title
author { name }
}
}イベントの購読
サブスクリプションのリゾルバは AsyncIterator を返す subscribe 関数を公開します。ミューテーション(またはサーバーのコード)が pubsub を通じて同じトピックへイベントを発行します。任意の resolve 関数が発行されたペイロードをフィールドの形に変換します。
# Server-side resolver with asyncIterator
const resolvers = {
Subscription: {
postAdded: {
subscribe: () => pubsub.asyncIterator(["POST_ADDED"]),
resolve: (payload) => payload.postAdded,
},
},
};
# Trigger from a mutation
const resolvers = {
Mutation: {
createPost: async (_, args, { pubsub }) => {
const post = await createPost(args);
await pubsub.publish("POST_ADDED", { postAdded: post });
return post;
},
},
};PubSub
graphql-subscriptions の PubSub は 1 つのサーバーインスタンス用です。ロードバランサー背後の複数インスタンスでは、共有ブローカーが必要です。redis-pubsub、MQTT、Kafka 製の pubsub などで、どのインスタンスに接続したクライアントにもイベントを届けましょう。
import { PubSub } from "graphql-subscriptions";
const pubsub = new PubSub();
// publish an event
pubsub.publish("POST_ADDED", { postAdded: post });
// consume in a subscription resolver
subscribe: () => pubsub.asyncIterator(["POST_ADDED"])
# For multi-instance production, swap PubSub for
# Redis, NATS, or Kafka-based implementations.フィルタ付きサブスクリプション
withFilter を使うと、接続中の各クライアントは自分に関係するイベントだけを受け取れます(例: 自分宛てのメッセージ)。フィルタ関数は発行されたペイロードとサブスクリプションの変数を受け取ります。フィルタは接続中の各クライアント × 各発行イベントで走るので、軽量に保ちましょう。
const resolvers = {
Subscription: {
messageReceived: {
subscribe: withFilter(
() => pubsub.asyncIterator(["MESSAGE_RECEIVED"]),
(payload, variables) =>
payload.messageReceived.recipientId === variables.userId
),
resolve: (payload) => payload.messageReceived,
},
},
};
# Only events where the filter returns true reach this clientWebSocket トランスポート
サブスクリプションは WebSocket 上の graphql-ws(または旧 subscriptions-transport-ws)プロトコルを使います。新しい graphql-ws プロトコルが推奨です。connectionParams で認証トークンを運びます。サーバーは HTTP エンドポイントと並べて WS ハンドラを設置する必要があります。
# Client uses graphql-ws over WebSocket
import { createClient } from "graphql-ws";
const wsClient = createClient({
url: "ws://localhost:4000/graphql",
connectionParams: { authToken: "..." },
});
wsClient.subscribe(
{ query: "subscription { postAdded { id title } }" },
{
next: (data) => console.log(data),
error: (err) => console.error(err),
complete: () => console.log("done"),
}
);引数
フィールド引数
引数は常に名前付きで、位置引数はありません。ルートフィールドだけでなく、任意のフィールドに付けられます。名前付き引数により、クエリは自己文書化され、順序に依存しません。値が動的なときはインラインリテラルの代わりに変数を使いましょう。
type Query {
user(id: ID!): User
posts(limit: Int, offset: Int): [Post!]!
}
# Arguments can be inline literals
query {
user(id: "1") { name }
posts(limit: 10, offset: 0) { title }
}デフォルト値
デフォルト値のある引数は省略可能になり、クライアントは省略できます。デフォルト値はリクエストごとに評価されます。非 null の引数にはデフォルト値がなく、クライアントは値を渡さなければなりません。デフォルト値でクエリを簡潔に保ちつつ、必要なときは明示できます。
type Query {
# default values make arguments optional
posts(limit: Int = 10, sort: String = "newest"): [Post!]!
user(id: ID!, includeDeleted: Boolean = false): User
}
# These are equivalent:
query { posts { title } }
query { posts(limit: 10, sort: "newest") { title } }引数の型
引数にはスカラー、enum、リスト、input オブジェクト型が使えます。通常のオブジェクト型は使えません(出力専用です)。input オブジェクトは複雑で構造化された引数、特にフィルタやページネーションを渡す慣用的な方法です。
type Query {
# scalar arguments
byId(id: ID!): User
byAge(min: Int!, max: Int!): [User!]!
# enum argument
byStatus(status: UserStatus!): [User!]!
# input object argument
search(filter: UserFilter!): [User!]!
# list argument
byIds(ids: [ID!]!): [User!]!
}必須と省略可能
引数の ! 接尾辞は必須を意味します。必須の引数を省くと、リゾルバが走る前にバリデーションが失敗し、明確なエラーが返ります。本当に必要な入力には必須を、調整可能な振る舞いには「デフォルト付きの省略可能」を使いましょう。
type Query {
# required (non-null) - client MUST provide
user(id: ID!): User
# optional (nullable) - client may omit
posts(limit: Int): [Post!]!
# optional with default
recentPosts(limit: Int = 5): [Post!]!
}
# Omitting a required argument is a validation error
# before any resolver runs.リスト引数
リストの引数は角括弧を使います。[ID!]! は非 null 要素の非 null リストで、クライアントはリストを渡し、すべての要素が非 null でなければな りません。リストは変数で渡すのがきれいで、エスケープ問題も避けられます。
type Query {
usersByIds(ids: [ID!]!): [User!]!
tags(allOf: [String!]): [Post!]!
}
# Inline list literal
query {
usersByIds(ids: ["1", "2", "3"]) { name }
}
# Via variable
query($ids: [ID!]!) {
usersByIds(ids: $ids) { name }
}
# { "ids": ["1", "2", "3"] }変数
変数の定義
変数は操作をパラメータ化します。操作ヘッダーで $name: Type と宣言し、本体で $name と参照し、値は別の JSON variables フィールドで送ります。静的なクエリと動的なデータが分離されます。
# Declare variables in the operation, then use them
query GetUser($id: ID!) {
user(id: $id) {
name
email
}
}
# Variables are sent in a separate JSON object
{
"id": "1"
}変数の型
変数の型はスキーマの引数の型と一致しなければなりません。変数は null 許容、非 null、リスト、input オブジェクトになれます。変数の型は input 型(スカラー、enum、input オブジェクト)でなければならず、出力のオブジェクト型は使えません。
query Search(
$term: String!
$limit: Int = 10
$filters: PostFilter
$tags: [String!]
) {
search(term: $term, limit: $limit, filters: $filters, tags: $tags) {
title
}
}デフォルト値
変数のデフォルト値は、クライアントが変数を省いたときに適用されます。null 許容の変数にしか付けられません。非 null の変数はクライアントが必ず値を供給するという意味です。デフォルト値により、クライアントは最小限の変数を送り、サーバーは柔軟さを保てます。
query Posts($limit: Int = 10, $sort: String = "newest") {
posts(limit: $limit, sort: $sort) { title }
}
# If the client omits "limit", it defaults to 10.
# Only nullable variables can have defaults - a non-null
# variable with a default is a contradiction.必須変数
非 null の変数(!)は必須です。省くとリゾルバが走る前にバリデーションが失敗します。入力の存在を保証する最も安全な方法です。非 null 変数にはデフォルト値を付けられません。デフォルトが欲しければ、変数を null 許容にしましょう。
query User($id: ID!) { # ! means required
user(id: $id) { name }
}
# Missing required variable -> validation error
{ "id": "1" } # OK
{ } # ERROR: variable $id of type ID! is required
# A non-null variable cannot have a default value.変数とディレクティブ
変数は @include や @skip のようなディレクティブを駆動でき、クライアントがフィールドを動的に切り替えられます。機能フラグ、A/B テスト、条件付きセクションが、キャッシュされた 1 つのクエリドキュメントのままで実現します。
query User($id: ID!, $withPosts: Boolean!) {
user(id: $id) {
name
posts @include(if: $withPosts) {
title
}
}
}
# { "id": "1", "withPosts": false } -> posts omitted
# { "id": "1", "withPosts": true } -> posts includedフラグメント
名前付きフラグメント
フラグメントは特定の型に束縛された再利用可能な選択セットです(fragment Name on Type)。その型が現れる場所ならどこでも ...Name で展開できます。クエリが DRY になり、複数の操作でフィールドの選択を共有できます。
# Define a reusable fragment
fragment UserFields on User {
id
name
email
}
# Spread it into queries
query {
user(id: "1") {
...UserFields
}
users {
...UserFields
}
}フラグメントの合成
フラグメントは他のフラグメントを展開でき、複合的な選択を組み立てられます。フィールドの選択をモジュール化し(基本プロフィールと詳細プロフィールなど)、各 UI コンポーネントが自分のデータ要件を宣言して、それを 1 つのクエリに合成できます。
fragment UserBasic on User {
id
name
}
fragment UserWithEmail on User {
...UserBasic
email
}
fragment UserFull on User {
...UserWithEmail
posts { title }
}
# Fragments can spread other fragments of the same type.フラグメント変数
Relay 流のフラグメント変数を使うと、フラグメントがパラメータ(limit など)を受け取れて、呼び出し側が @arguments で渡せます。フラグメントが異なる設定で真に再利用可能になります。Apollo はクライアントディレクティブの @arguments でこれをサポートしています。
fragment UserPosts on User
@argumentDefinitions(limit: { type: "Int", defaultValue: 5 }) {
posts(limit: $limit) {
title
}
}
query {
user(id: "1") {
...UserPosts @arguments(limit: 10)
}
}
# @argumentDefinitions and @arguments come from
# Relay; Apollo uses a similar pattern via client directives.再利用可能なフラグメント
フラグメントをそれを描画するコンポーネントの横に置く(コロケーションする)のは強力なパターンです。各コンポーネントがデータ要件を宣言し、親がそれらを 1 つのクエリに合成します。大きなアプリでデータ取得がスケールします(Relay と Apollo の両方が対応)。
// Colocate fragments with the UI component that uses them
const USER_CARD = graphql`
fragment UserCard_user on User {
id
name
avatarUrl
}
`;
function UserCard({ user }) {
return <div>{user.name}</div>;
}
// The parent query spreads all needed fragments
query {
users {
...UserCard_user
}
}フラグメントの注意点
Post に対して宣言したフラグメントは、Post が期待される場所にしか展開できません。User に展開するとバリデーションエラーです。union/interface に対して条件付きで展開するには、型条件付きのインラインフラグメントを使います。循環するフラグメント展開も避けましょう。
# A fragment must match the type where it's spread
fragment PostFields on Post { title body }
query {
user(id: "1") {
...PostFields # ERROR: user is not a Post
}
}
# Fragments can only spread on the declared type
# (or via type conditions with inline fragments).インラインフラグメント
インラインフラグメントの基本
インラインフラグメントは名前のない選択セットで、... on Type と書きます。実行時のオブジェクトが型条件に一致するときにだけ、フィールドが適用されます。interface や union で型固有のフィールドにアクセスする方法です。
# An inline fragment is a selection set with a type condition
query {
user(id: "1") {
id
name
# fields common to User
... on AdminUser {
permissions
}
}
}
# No name - declared inline in the query.型条件
... on Type の構文が型条件です。1 つの選択の中に複数のインラインフラグメントを置くと、union/interface のありうる各型を別々に処理できます。すべての型に共通するフィールドは、フラグメントの外で直接選択できます。
query Search($term: String!) {
search(term: $term) {
... on User { name email }
... on Post { title author { name } }
... on Comment { body }
}
}Union へのアクセス
union には __typename 以外の共通フィールドがないため、型固有のデータを読むにはインラインフラグメントが必須です。__typename は常に選択でき、各項目の具象型をクライアントに伝えます。union の結果の描画に不可欠です。
union SearchResult = User | Post | Comment
query {
search(term: "graphql") {
# shared __typename is always available
__typename
... on User { name }
... on Post { title }
... on Comment { body }
}
}Interface へのアクセス
interface は共通フィールドを宣言します。共通フィールドは interface に対して直接選択でき、型固有のフィールドにはインラインフラグメントが必要です。union と違い、interface は実装するすべての型が提供すべき共通のフィールド集合を保証します。
interface Node { id: ID! }
type User implements Node { id: ID! name: String! }
type Post implements Node { id: ID! title: String! }
query {
node(id: "1") {
id # shared interface field - selectable directly
... on User { name }
... on Post { title }
}
}型条件付きの名前付きフラグメント
名前付きフラグメントは自分の型条件を持つので、union/interface の結果に展開でき、それぞれが一致する型にだけ適用されます。再利用性と条件付き選択を両立できます。複数の名前付きフラグメントを展開すれば、union のすべてのメンバーをカバーできます。
# Named fragments can also carry a type condition
fragment UserFields on User { name email }
fragment PostFields on Post { title }
query {
search(term: "a") {
...UserFields
...PostFields
}
}
# Equivalent to inlining those fragments inline.ディレクティブ
組み込みディレクティブ
GraphQL には 2 つの組み込みクライアントディレクティブがあります。@skip(if: Boolean!) は true のときフィールドを省き、@include(if: Boolean!) は true のときだけ含めます。相互に排他的で、フィールド、フラグメント展開、インラインフラグメントに適用できます。
# @skip - omit field if true
query($skip: Boolean!) {
user(id: "1") {
name
email @skip(if: $skip)
}
}
# @include - include field only if true
query($withPosts: Boolean!) {
user(id: "1") {
posts @include(if: $withPosts) { title }
}
}@skip と @include
@skip と @include で、1 つのクエリが複数の形に対応します。Boolean 変数を受け取るので、同じ永続化クエリが変数に応じてサマリー表示も詳細表示も行えます。クエリ文字列を 2 つ管理する必要がありません。
query User($id: ID!, $detailed: Boolean!) {
user(id: $id) {
name
email @skip(if: $detailed) # hide when detailed
profile @include(if: $detailed) { # show when detailed
bio
}
}
}
# { "id": "1", "detailed": false } -> name, email
# { "id": "1", "detailed": true } -> name, profile { bio }カスタムディレクティブ
カスタムディレクティブは directive 宣言で引数と適用可能な場所を定義します。実行時の意味論は組み込みではなく、スキーマ変換(Apollo)やディレクティブビジター(graphql-tools)で実装します。よくある用途: @auth、@cached、@deprecated。
# Declare a directive in SDL
directive @auth(requires: Role = ADMIN) on FIELD_DEFINITION
type Query {
adminData: String @auth(requires: ADMIN)
userData: String @auth(requires: USER)
}
# A directive needs a location: FIELD_DEFINITION, FIELD,
# OBJECT, ENUM, etc. Logic is implemented in the server
# (e.g. via schema transforms or a directive visitor).ディレクティブの適用場所
すべてのディレクティブは適用できる場所を宣言します。操作、フィールド、フラグメント、スキーマ定義(FIELD_DEFINITION、OBJECT など)です。クライアントディレクティブ(クエリに適用)とスキーマディレクティブ(SDL に適用)では場所の集合が異なります。スキーマ構築時に検証しましょう。
# Where a directive can appear
directive @example on
| QUERY # operation
| FIELD # a field in a selection
| FRAGMENT_DEFINITION
| FRAGMENT_SPREAD
| INLINE_FRAGMENT
| FIELD_DEFINITION # in SDL (server-side)
| OBJECT | INTERFACE | UNION | ENUM
| ENUM_VALUE | INPUT_OBJECT | INPUT_FIELD_DEFINITION;
# Multiple locations use | between them.ディレクティブの引数
ディレクティブはデフォルト値付きの型付き引数を持てます。組み込みの @deprecated(reason:) はフィールドと enum 値を廃止予定としてマークし、ツールが使っているクライアントに警告します。引数付きのカスタムディレクティブは、キャッシュ TTL や必須ロールのような振る舞いを駆動します。
directive @deprecated(
reason: String = "No longer supported"
) on FIELD_DEFINITION | ENUM_VALUE
type Query {
oldField: String @deprecated(reason: "Use newField")
newField: String
}
enum Status {
ACTIVE
INACTIVE @deprecated(reason: "Use ARCHIVED")
ARCHIVED
}列挙型(Enum)
enum の定義
enum は名前付き値の有限集合です。enum はスカラー型で、サブセレクションを持たないリーフ値です。固定された選択肢の集合(status、role、kind)を持つフィールドには、マジック文字列の代わりに enum を使いましょう。バリデーションと自己文書化が得られます。
enum Role {
ADMIN
USER
GUEST
}
enum PostStatus {
DRAFT
PUBLISHED
ARCHIVED
}
type User {
role: Role!
}
type Post {
status: PostStatus!
}enum の値
enum 値はクエリ内ではクォートなしの識別子として書きます(color: RED)が、JSON の変数やレスポンスでは文字列としてシリアライズされます。命名は UPPER_SNAKE_CASE が慣例です。サーバーは値を宣言された集合に対して検証します。
enum Color {
RED
GREEN
BLUE
}
# In a query, enum values are unquoted identifiers
query {
products(color: RED) { name }
}
# In variables JSON, they're sent as strings
{ "color": "RED" }クエリでの enum の使用
enum はフィールドの型にも引数の型にも使えます。引数として使うと、クライアントは宣言された値の 1 つを渡します。不正な enum 値はリゾルバが走る前にバリデーションで失敗し、明確なエラーが得られます。
type Query {
posts(status: PostStatus!): [Post!]!
}
query {
posts(status: PUBLISHED) { title }
}
query($status: PostStatus!) {
posts(status: $status) { title }
}
# { "status": "DRAFT" }enum のリゾルバ
デフォルトでは enum 値はその自身にマップされます。enum のリゾルバを使うと、公開 API の名前(ADMIN)と内部表現(文字列 "admin" や数値のロールコード)を相互にマップできます。スキーマをストレージの詳細から切り離せます。
# Map internal values <-> API values
enum Role {
ADMIN
USER
}
const resolvers = {
Role: {
ADMIN: "admin", // internal DB value
USER: "user",
},
};
# Internally the resolver sees "admin"; the client sees ADMIN.
# Useful when DB values differ from the public API.enum のベストプラクティス
固定の選択肢の集合には、自由形式の文字列より常に enum を優先しましょう。入力が検証され、API が文書化され、ツールの支援も良くなります。クライアントを壊さずに enum 値を取り除くには、まず deprecate します。クライアントがまだ送ってくる値の削除は破壊的変更です。
# Prefer enums over strings for fixed option sets
type User {
role: Role! # GOOD - validated, self-documenting
roleStr: String # AVOID - no validation, magic strings
}
# Deprecate values instead of removing them
enum Status {
ACTIVE
INACTIVE @deprecated(reason: "Use ARCHIVED")
ARCHIVED
}インターフェース
インターフェースの定義
interface は、実装する型が提供すべきフィールドの集合を宣言する抽象型です。契約を定義します。Node(relay 流のグローバル ID)や、関連する型にまたがる Character のような、共通の抽象化に便利です。
interface Node {
id: ID!
}
interface Character {
name: String!
}
type User implements Node & Character {
id: ID!
name: String!
email: String!
}インターフェースの実装
型は implements キーワードでインターフェースを実装することを宣言します。インターフェースが宣言するすべてのフィールドを、互換性のある型で定義する必要があります。1 つの型は複数のインターフェースを実装できます(& で区切る)。スキーマはビルド時にこれを検証します。
interface Node {
id: ID!
}
type User implements Node {
id: ID! # required by Node
name: String!
}
type Post implements Node {
id: ID! # required by Node
title: String!
}
# A type must implement every field of the interface.インターフェースのクエリ
フィールドがインターフェースを返すとき、インターフェースの共通フィールドは直接選択できます。型固有のフィールドにはインラインフラグメント(... on User)を使います。各結果の実行時の型が、どのインラインフラグメントが適用されるかを決めます。
interface Node { id: ID! }
type Query {
node(id: ID!): Node
}
query {
node(id: "1") {
id # interface field - always selectable
... on User { name }
... on Post { title }
}
}インターフェースのリゾルバ
interface には、実行時の値に対する具象型の名前(または型オブジェクト)を返す __resolveType 関数が必要です。これで GraphQL はどのインラインフラグメントを適用するか判断します。なければ、GraphQL は実行時に具象型を決められません。
interface Character { name: String! }
type Human implements Character {
name: String!
starships: [String!]!
}
type Droid implements Character {
name: String!
primaryFunction: String
}
const resolvers = {
Character: {
// tell GraphQL which concrete type a value is
__resolveType(obj) {
return obj.primaryFunction ? "Droid" : "Human";
},
},
};複数のインターフェース
1 つの型は & 区切りで複数のインターフェースを実装できます。能力を合成できます。たとえば Node であり、Timestamped であり、SoftDeletable でもある Article のように。クエリはインターフェース型を返し、クライアントは具象フィールドにインラインフラグメントを使います。
interface Node { id: ID! }
interface Timestamped { createdAt: String! }
interface SoftDeletable { deletedAt: String }
type Article implements Node & Timestamped & SoftDeletable {
id: ID!
createdAt: String!
deletedAt: String
title: String!
}
# Use & to list multiple implemented interfaces.ユニオン
union の定義
union は複数の具象型のどれかになれる抽象型で、共通フィールドを要求しません(interface とは違う)。union Name = TypeA | TypeB と定義します。結果が異質だが概念的には関連しているときに、union が最適です。
union SearchResult = User | Post | Comment
type User { id: ID! name: String! }
type Post { id: ID! title: String! }
type Comment { id: ID! body: String! }
type Query {
search(term: String!): [SearchResult!]!
}union と interface
メンバーが共通の契約(全メンバーが持つフィールド)を共有するなら interface を、概念的にしか関連しないなら union を使いましょう(フィールドを共有しない)。1 つの型は多くの union に属せますが、union は他の union を直接実装できません。
# INTERFACE - shared contract
interface Node { id: ID! }
type User implements Node { id: ID! name: String! }
type Post implements Node { id: ID! title: String! }
# All members share the "id" field.
# UNION - no shared contract
union SearchResult = User | Post
# Members share NO required fields.union のクエリ
union は自分のフィールドを何も公開しないので、何かを読むには必ずインラインフラグメントを使います。__typename は常に利用可能で、各項目の具象型をクライアントに伝えます。union に対して型条件なしでフィールドを直接選択するのはバリデーションエラーです。
query {
search(term: "graphql") {
__typename # always available
... on User { name email }
... on Post { title }
... on Comment { body }
}
}
# You CANNOT select fields directly on a union
# (no shared fields) - only via inline fragments.union のリゾルバ
interface と同様に、union にも実行時の値に対する具象型の名前を返す __resolveType リゾルバが必要です。なければ GraphQL はインラインフラグメントを選べません。型名を文字列で、またはスキーマから型オブジェクトで返します。
union SearchResult = User | Post | Comment
const resolvers = {
SearchResult: {
__resolveType(obj) {
if (obj.email) return "User";
if (obj.title) return "Post";
if (obj.body) return "Comment";
return null;
},
},
};よくあるパターン
union は「結果またはエラー」をモデル化します。ミューテーションが成功型とエラー型の union を返し、クライアントに両方の処理を強制します。任意のエラーフィールドを持つ 1 つのペイロードより型安全です。(SDL では type エイリアスではなく union が要求されます。)
# Mutation result that may be success or error
type CreateUserSuccess { user: User! }
type CreateUserError { messages: [String!]! }
type CreateUserPayload = CreateUserSuccess | CreateUserError
# (note: a type alias like this isn't valid SDL; use union)
union CreateUserPayload = CreateUserSuccess | CreateUserError
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
}input 型
input オブジェクト型
input 型は引数に使うオブジェクト型で、input で宣言します。関連するフィールド(ユーザー、フィルタ)を 1 つの引数にまとめます。出力のオブジェクト型と違い、input 型には input 型(スカラー、enum、他の input 型)しか入れられません。
input CreateUserInput {
name: String!
email: String!
age: Int
}
type Mutation {
createUser(input: CreateUserInput!): User!
}
mutation($input: CreateUserInput!) {
createUser(input: $input) { id }
}
# { "input": { "name": "Alice", "email": "[email protected]" } }input と output の違い
出力型(type)はフィールド引数とリゾルバを持てますが、input 型(input)はリゾルバのない単なるデータの入れ物です。別々の名前空間なので、User 型と UserInput input を併存させられます。1 つを両方に再利用してはいけません。進化が壊れます。
# OUTPUT type - returned from resolvers, has resolvers
type User {
id: ID!
name: String!
posts: [Post!]! # can have field arguments and resolvers
}
# INPUT type - passed into operations, no resolvers
input UserInput {
name: String!
email: String!
# NO field arguments, NO resolvers, NO output object types
}
# A type cannot be used as both input and output.ネストした input
input 型は他の input 型やリストを参照でき、複雑なネストしたペイロードをモデル化できます。階層的なフォームやネストしたフィルタに理想的です。各レベルがスキーマに対して検証され、不正な入力に明確なエラーが得られます。
input AddressInput {
street: String!
city: String!
zip: String!
}
input CreateUserInput {
name: String!
email: String!
address: AddressInput # nested input type
tags: [String!] # list input
}
type Mutation {
createUser(input: CreateUserInput!): User!
}input のデフォルト値
input のフィールドと引数にはデフォルト値を付けられます。クライアントがフィールドを省くとデフォルトが適用されます。デフォルトにより、クライアントに完全なオブジェクトを送らせずに入力を省略可能にできます。デフォルトは静的なリテラルで、リクエストごとに計算されるものではない点に注意しましょう。
input PaginationInput {
limit: Int = 20
offset: Int = 0
sort: SortOrder = DESC
}
enum SortOrder { ASC DESC }
type Query {
posts(page: PaginationInput = { limit: 20, offset: 0 }): [Post!]!
}
# Defaults apply per-field when omitted by the client.input のバリデーション
GraphQL は型と非 null 性を検証しますが、意味論的なルール(メール形式、年齢範囲、文字列長)は検証しません。それらはリゾルバで実装し、悪いデータには UserInputError を投げましょう。サーバーによっては宣言的なルールのためのバリデーションディレクティブ(@constraint)を追加できます。
input CreateUserInput {
name: String! # required, non-null
email: String! # format check needs custom code
age: Int # range check needs custom code
}
# GraphQL validates structure; you validate semantics
function createUser(_, { input }) {
if (!input.email.includes("@")) {
throw new UserInputError("Invalid email");
}
if (input.age < 0 || input.age > 150) {
throw new UserInputError("Invalid age");
}
// ...
}リゾルバ
リゾルバ関数
リゾルバは 1 つのフィールドの値を生成する関数です。リゾルバマップはスキーマを反映します: resolvers.Query.user が user フィールドを処理します。リゾルバがない場合、GraphQL は親から対応するプロパティを読むデフォルト動作を使います。
const resolvers = {
Query: {
user: (parent, args, context, info) => {
return context.db.user.findById(args.id);
},
users: () => db.users.findAll(),
},
Mutation: {
createUser: (_, { input }, { db }) =>
db.user.create(input),
},
};リゾルバの引数
すべてのリゾルバは 4 つの引数を受け取ります: parent(親フィールドの解決済みの値)、args(このフィールドの引数)、context(リクエストごとの共有オブジェクト)、info(AST と実行メタデータ)。最初の 2 つが最もよく使われ、info はサブセレクションの検査などの高度な用途向けです。
// (parent, args, context, info)
const resolvers = {
Query: {
user: (parent, args, context, info) => {
// parent - value returned by the parent field (root for Query)
// args - arguments passed to this field
// context - shared per-request object (db, user, loaders)
// info - AST + execution info (rarely needed)
return context.db.user.findById(args.id);
},
},
};リゾルバのチェーン
リゾルバは深さ優先のチェーンで実行されます。親フィールドのリゾルバがオブジェクトを生成し、その後、各子フィールドのリゾルバがそのオブジェクトを parent として実行します。このトップダウンの流れにより、各フィールドが独立に解決され、グラフがフィールドごとに組み上がります。
# query { user(id: "1") { name posts { title } } }
const resolvers = {
Query: {
user: () => ({ id: "1", name: "Alice" }), // runs first
},
User: {
posts: (user, args, ctx) => { // runs after user
return ctx.db.posts.findByAuthor(user.id);
},
},
Post: {
title: (post) => post.title, // runs after posts
},
};非同期リゾルバ
リゾルバは Promise を返せます。GraphQL は子フィールドへ進む前にそれを待ちます。データベースや API の呼び出しはこれで行います。可読性のため async/await を使いましょう。同じレベルのリゾルバは(クエリでは)並列に実行されるので、独立した非同期処理は自然にバッチ化されます。
const resolvers = {
Query: {
// return a Promise - GraphQL awaits it
user: async (_, { id }, { db }) => {
const user = await db.user.findById(id);
if (!user) throw new Error("User not found");
return user;
},
},
User: {
posts: async (user, _, { db }) =>
db.posts.findByAuthor(user.id),
},
};デフォルトリゾルバ
フィールドにリゾルバがない場合、GraphQL は親オブジェクトから同名のプロパティを読みます(undefined なら null)。ロジックや取得が必要なフィールドだけリゾルバを書きましょう。親オブジェクトが既に正しい形をしていれば、デフォルトの動作で十分です。
# If you don't define a resolver, GraphQL reads from the parent
const resolvers = {
User: {
// name resolver missing - default behavior:
// (parent) => parent.name
posts: (user) => fetchPosts(user.id), // only this is custom
},
};
// Equivalent explicit default:
User: {
name: (user) => (user.name === undefined ? null : user.name),
}リゾルバのベストプラクティス
リゾルバは薄く保ちましょう。取得は context 上のデータソースクラスに委譲します。データアクセスが一元化され(テスト可能、モック可能)、データソースがバッチとキャッシュを担えます。リゾルバはオーケストレーションに徹し、SQL や fetch のロジックを直接書く場所にしないようにしましょう。
# Keep resolvers thin - delegate to data sources
const resolvers = {
Query: {
user: (_, { id }, { dataSources }) =>
dataSources.userAPI.getUser(id),
},
User: {
posts: (user, _, { dataSources }) =>
dataSources.postAPI.byAuthor(user.id),
},
};
// dataSources live on context, are injected per request,
// and can batch/cache calls internally.Context と DataLoader
Context オブジェクト
context は 1 つの操作の中のすべてのリゾルバで共有される、リクエストごとのオブジェクトです。共有依存をここに置きます: データベースクライアント、認証済みユーザー、DataLoader、ロガーなど。context 関数はリクエストごとに 1 回実行され、戻り値がすべ てのリゾルバに渡ります。
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => ({
db: new PrismaClient(),
user: getUserFromToken(req.headers.authorization),
loaders: buildLoaders(),
}),
});
// Inside any resolver, the third argument is context:
(parent, args, context) => context.db.user.findById(args.id);リクエストごとの Context
DataLoader のインスタンスは context 関数の中で毎回新しく作りましょう。キャッシュが 1 つのリクエストに閉じます。ローダーをリクエスト間で使い回すと、キャッシュされたデータがユーザー間で漏れます。context 自体はリクエストごとに 1 回構築されるので、リクエストごとのセットアップはここに置きます。
const context = async ({ req }) => {
const token = req.headers.authorization || "";
const user = await verifyToken(token); // may be null
return {
user,
db,
// a FRESH DataLoader instance per request
// so caches don't leak across requests
userLoader: new DataLoader((ids) => batchGetUsers(ids)),
};
};N+1 問題
N+1 問題とは、N 個のアイテムのリストを取得した後、リレーションを読むために各アイテムにつき 1 回の追加クエリを発行してしまうことです。GraphQL の並列フィールド解決はこれを起こしやすいです。User.posts のリゾルバはユーザーごとに 1 回走るからです。結果として冗長なクエリの氾濫になります。
# query { users { id name posts { title } } }
// BAD: 1 query for users, then N queries for each user's posts
const resolvers = {
User: {
posts: (user, _, { db }) =>
db.posts.findByAuthor(user.id), // runs once per user!
},
};
// If there are 100 users, that's 101 DB queries.
// This is the classic N+1 problem.DataLoader の基本
DataLoader は個別のロードの山を 1 つのバッチリクエストにまとめます。キーの配列を受け取り、同じ順序の結果の配列を返すバッチ関数を与えます。DataLoader は 1 ティック内のすべてのロードを集め、バッチ関数を 1 回だけ呼びます。
import DataLoader from "dataloader";
// A batch function receives an array of keys, returns
// an array of values IN THE SAME ORDER as the keys.
const userLoader = new DataLoader(async (userIds) => {
const users = await db.users.findMany({ where: { id: { in: userIds } } });
// reorder to match the input keys
return userIds.map((id) =>
users.find((u) => u.id === id) ?? null
);
});リゾルバでの DataLoader
リゾルバでは DB を直接呼ぶ代わりに loader.load(key) を使います。1 つのティック内では、同じローダーへのすべての ロードが 1 つのクエリにバッチ化され、結果はリクエストの間キャッシュされます。リゾルバをシンプルに保ったまま N+1 を撲滅できます。
const resolvers = {
User: {
posts: (user, _, { loaders }) =>
loaders.postLoader.load(user.id),
},
Post: {
author: (post, _, { loaders }) =>
loaders.userLoader.load(post.authorId),
},
};
// 100 users -> ONE batched query for all their posts,
// instead of 100 separate queries.バッチングとキャッシュ
DataLoader は 2 つのことをします。バッチング(1 つのイベントループのティック内の多数のロードが 1 回のバッチ呼び出しになる)と、キーごとのキャッシュ(同じキーの再ロードは同じ Promise を返す)です。キャッシュはローダーインスタンスごとなので、リクエストごとに新しいローダーを作るわけです。
// Batching: many .load() calls in one tick -> one batch fn call
await Promise.all([loader.load(1), loader.load(2), loader.load(3)]);
// -> batchGetUsers([1, 2, 3]) called ONCE
// Caching: repeated .load(sameKey) returns the cached Promise
loader.load(1); loader.load(1); loader.load(1);
// -> batchGetUsers([1]) called ONCE; later calls hit cache
// .clear(key) invalidates; .clearAll() resets everything.エラーハンドリング
エラーレスポンスの形式
エラーは data と並ぶトップレベルの errors 配列で返ります。各エラーには message、クエリ内の location、失敗したフィールドへの path、機械可読なコードのための extensions があります。フィールドのエラーはそのフィールドを null にし(非 null なら親に波及)、それでも data には成功した部分が返ります。
# Errors appear in a top-level "errors" array
{
"errors": [
{
"message": "User not found",
"locations": [{ "line": 2, "column": 3 }],
"path": ["user"],
"extensions": {
"code": "NOT_FOUND",
"exception": { "stacktrace": ["..."] }
}
}
],
"data": { "user": null }
}エラーのスロー
最もシンプルなエラー処理 は Error を投げることです。GraphQL がそれをキャッチし、フィールドを null にして、errors 配列にエントリを追加します。より構造化するには、extensions にエラーコードを持つ専用のエラークラス(ApolloError、UserInputError)を使いましょう。
const resolvers = {
Query: {
user: async (_, { id }, { db }) => {
const user = await db.user.findById(id);
if (!user) {
throw new Error("User not found");
}
return user;
},
},
};
# Thrown errors become entries in the "errors" array.カスタムエラー
型付きのエラークラスで意図を伝えましょう: 悪いクライアント入力には UserInputError(4xx)、認証の欠如には AuthenticationError、権限なしには ForbiddenError、カスタムな場合はコード付きの ApolloError。extensions のコードにより、クライアントはエラーに対して確実に分岐できます。
import { ApolloError, UserInputError } from "apollo-server-errors";
const resolvers = {
Mutation: {
createUser: (_, { input }) => {
if (!isValidEmail(input.email)) {
throw new UserInputError("Invalid email", {
field: "email",
});
}
if (emailTaken(input.email)) {
throw new ApolloError("Email taken", "EMAIL_TAKEN", {
email: input.email,
});
}
// ...
},
},
};エラーの extensions
extensions は機械可読なデータを運びます: 安定したコード文字列、再試行のヒント、バリデーションのフィールドパスなど。クライアントは、変わりうる人間向けのメッセージをパースするのではなく、extensions.code で分岐しましょう。本番のレスポンスにスタックトレースを含めないようにしましょう。
# Structured, machine-readable error data
throw new ApolloError("Rate limited", "RATE_LIMITED", {
code: "RATE_LIMITED",
retryAfter: 60,
limit: 100,
});
# Clients check extensions.code to handle errors
if (err.extensions.code === "RATE_LIMITED") {
wait(err.extensions.retryAfter);
}部分的な結果
GraphQL は部分的な結果を返します。成功したフィールドは data に現れ、失敗したフィールドは null になります(非 null なら親に波及)し、errors に列挙されます。1 つの失敗でレスポンス全体が null にならないよう、フィールドは null 許容にするのが好ましいです。非 null は 強い契約なので、意図を持って使います。
# A non-null field error nulls the parent; nullable just nulls the field
type Query {
user(id: ID!): User # nullable - error nulls only "user"
me: User! # non-null - error bubbles up to null "me"
}
# Query selecting multiple fields:
query { me { name } user(id: "bad") { name } }
# If "user" errors but "me" succeeds:
{
"data": { "me": { "name": "Alice" }, "user": null },
"errors": [{ "path": ["user"], "message": "..." }]
}Apollo Server と統合
Apollo Server のセットアップ
Apollo Server は最も人気のある Node.js の GraphQL サーバーです。typeDefs(SDL)と resolvers を渡して構築し、手早い開発にはスタンドアローンサーバーで起動します。本番ではスタンドアローンではなく、既存の HTTP フレームワーク(Express、Fastify、Next.js)と統合しましょう。
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";
const typeDefs = `#graphql
type Query { hello: String }
`;
const resolvers = {
Query: { hello: () => "Hello, world!" },
};
const server = new ApolloServer({ typeDefs, resolvers });
const { url } = await startStandaloneServer(server, {
listen: { port: 4000 },
});
console.log(`Server ready at ${url}`);Express との統合
Express では @apollo/server/express4 の expressMiddleware を使います。ミドルウェアをマウントする前にサーバーを起動します。context 関数は Express の req/res を受け取るので、ヘッダーやセッションを読み、認証を付けられます。既存の Express アプリに GraphQL を組み込めます。
import { ApolloServer } from "@apollo/server";
import { expressMiddleware } from "@apollo/server/express4";
import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
const app = express();
const server = new ApolloServer({ typeDefs, resolvers });
await server.start();
app.use("/graphql", cors(), bodyParser.json(),
expressMiddleware(server, {
context: async ({ req }) => ({ user: getUser(req) }),
})
);
app.listen(4000);スキーマの構築
makeExecutableSchema(@graphql-tools/schema)は typeDefs と resolvers からスキーマを構築し、ApolloServer に渡す GraphQLSchema オブジェクトを返します。この一段挟むことで、スキーマ変換、複数モジュールのマージ、カスタムディレクティブの適用が可能になり、大きなコードベースで有用です。
import { makeExecutableSchema } from "@graphql-tools/schema";
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
const server = new ApolloServer({ schema });
// makeExecutableSchema lets you apply schema transforms,
// directive visitors, and merge modules before serving.Context 関数
context 関数はリクエストごとに 1 回実行され、戻り値がすべてのリゾルバで共有されます。認証ヘッダーを読み、認証済みユーザー、データベースクライアント、新しい DataLoader をここで付けましょう。context の中で throw すると、どのリゾルバも走る前にリクエストを拒否できます(例: 認証不良)。
const server = new ApolloServer({ typeDefs, resolvers });
const { url } = await startStandaloneServer(server, {
context: async ({ req }) => {
const token = req.headers.authorization || "";
const user = await verifyToken(token);
return { user, db, loaders: makeLoaders() };
},
listen: { port: 4000 },
});Apollo Studio / Sandbox
Apollo Sandbox(サーバー URL でブラウザ内)では、開発中にスキーマを探索し操作を実行できます。Apollo Studio はクラウド側の対応物で、スキーマ履歴、メトリクス、トレーシングを提供します。外部にスキーマを隠したければ、本番でイントロスペクションを無効化しましょう。
# Apollo Sandbox is a dev IDE in the browser
# Visit the server URL in a browser to open it.
const server = new ApolloServer({
typeDefs,
resolvers,
// Apollo Studio reports go through this key (optional)
// apollo: { graphRef: "my-graph@current" },
});
# For introspection in production, enable it explicitly:
# new ApolloServer({ introspection: true });リクエストのライフサイクル
Apollo Server はリクエストごとにライフサイクルを実行します。context の構築、クエリのパース、スキーマに対する検証、リゾルバの実行、レスポンスの整形です。formatError がエラーの形をカスタマイズし、プラグインは didResolveOperation、willSendResponse などのフェーズにフックできます。ロギング、キャッシュ、メトリクスに便利です。
# Order: HTTP request -> context -> parse -> validate ->
# execute (resolvers) -> format response -> HTTP response
const server = new ApolloServer({
typeDefs,
resolvers,
formatError: (formatted, error) => ({
message: error.message,
code: formatted.extensions?.code,
}),
plugins: [loggingPlugin, cachePlugin],
});
# plugins hook into every lifecycle phase.関連する GraphQL スニペット
Copy-paste ready code for common tasks.
Schema and Types
Define types, enums, and scalars.
Queries
Read data with selection sets.
Mutations
Write data and return the result.
Subscriptions
Receive pushed updates over a stream.
Fragments
Reusable selection sets.
Variables
Parameterize operations dynamically.
Directives
Conditionally include or skip fields.
Resolvers
Functions that fulfill each field.
Was this helpful?