시작하기
기본 쿼리
GraphQL은 클라이언트가 필요한 데이터를 정확히 지정하게 합니다. 쿼리가 데이터를 가져오면 응답이 쿼리 모양을 그대로 반영합니다. REST API에서 흔한 오버페칭과 언더페칭을 피하게 해 줍니다.
# 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으로 선언합니다. 쿼리 문자열은 고정이고 호출마다 variables 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은 뮤테이션을 직렬로(차례차례) 실행하고, 쿼리 필드는 병렬로 실행합니다.
# Mutation - write data, then return the result
mutation {
createUser(input: { name: "Bob", email: "[email protected]" }) {
id
name
}
}
# Response
{
"data": {
"createUser": {
"id": "42",
"name": "Bob"
}
}
}필드와 선택 집합
선택 집합(selection set)은 중괄호 안의 필드 목록입니다. 스칼라와 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 vs REST
REST는 고정된 모양의 여러 엔드포인트를 노출하고, GraphQL은 클라이언트가 모양을 정의하는 하나의 엔드포인트를 노출합니다. 왕복을 줄이고 오버/언더페칭을 막습니다. 대가는 더 복잡한 서버와 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 키워드와 필드들로 정의합니다. 각 필드는 이름과 반환 타입을 갖습니다. ! 접미사는 널이 아님을 뜻하고, [Type!]은 널이 아닌 항목들의 리스트, [Type!]!은 널이 아닌 항목들로만 이뤄진 널이 아닌 리스트입니다.
# 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!
}설명 추가
삼중 따옴표 문자열(또는 정의 앞의 한 줄 문자열)이 설명으로서 스키마의 일부가 됩니다. 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은 다른 곳에 선언된 타입에 필드를 추가합니다. 큰 스키마를 파일들로 나누거나 모듈별 필드를 더할 때 쓰입니다. 타입은 한 번 선언하고 여러 번 확장할 수 있지만, 각 필드는 한 번만 정의할 수 있습니다.
# 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.스키마 우선 vs 코드 우선
스키마 우선은 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은 다섯 내장 스칼라를 제공합니다: 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
}스칼라 리졸버
스칼라 리졸버는 세 개의 선택적 메서드를 갖습니다. serialize는 내부 값을 JSON 출력으로, parseValue는 변수 입력을 내부 형태로, parseLiteral은 쿼리 AST의 인라인 리터럴을 내부 형태로 변환합니다. 완전히 타입화된 스칼라에는 셋 모두 정의하세요.
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!
}필드와 필드 타입
모든 필드가 반환 타입을 선언합니다. 기본은 널러블이며 !가 널이 아님을 만듭니다. 리스트는 []로 감쌉니다. !의 위치가 중요합니다: [String]은 널일 수 있고 null을 담을 수 있음, [String!]은 널일 수 있지만 항목은 널이 아님, [String!]!은 널도 널 항목도 불가입니다.
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이 됩니다. 기본은 널러블로 두고 값이 진짜 보장될 때만 널 아님을 선택하세요.
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
}객체의 필드 인수
루트 필드뿐 아니라 어떤 필드든 인수를 받을 수 있습니다. 이로써 하나의 타입이 관련 데이터의 필터링/페이징된 뷰를 노출합니다(예: 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 } }다중 필드
쿼리는 하나의 요청에서 여러 루트 필드를 선택할 수 있습니다. GraphQL은 이를 병렬로 실행합니다(뮤테이션 제외). 관련 가져오기를 하나의 왕복으로 묶는, 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" }, ... ]
}
}별칭(Alias)
별칭은 응답에서 필드 이름을 바꿉니다. 다른 인수로 같은 필드를 선택할 때 필수입니다 — 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의 슈퍼파워입니다. 클라이언트가 하나의 쿼리로 그래프를 걷습니다(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
}
}연산 이름
연산 이름(query GetUserProfile)은 선택이지만 강력히 권장됩니다. 이름 있는 연산은 디버깅이 쉽고 로그와 Apollo Studio에 표시되며, 하나의 문서에서 여러 연산을 보내거나 영속 쿼리에 쓸 때 필수입니다.
# 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). 뮤테이션은 쓰인 순서대로 직렬 실행되므로, 하나의 요청에서 여러 뮤테이션 필드 사이의 순서 의존 부수 효과가 안전합니다.
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 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, 성공 flag, 클라이언트 뮤테이션 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!
}다중 뮤테이션
쿼리(병렬)와 달리 하나의 연산에서 뮤테이션들은 선언 순서대로 직렬 실행됩니다. 이로써 두 번째 뮤테이션이 첫 번째의 효과를 봄이 보장됩니다. 한 뮤테이션 필드가 오류 나도 뒤의 것은 실행됩니다 — 입력을 검증하고 필요하면 트랜잭션을 쓰세요.
# 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 타입
구독은 이벤트가 발생하면 서버에서 클라이언트로 데이터를 밀어 보냅니다(보통 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은 단일 서버 인스턴스에서 동작합니다. 로드밸런서 뒤의 여러 서버 인스턴스에는 공유 브로커가 필요합니다 — 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 }
}기본값
기본값이 있는 인수는 선택이 됩니다 — 클라이언트가 생략할 수 있습니다. 기본값은 요청마다 평가됩니다. 널이 아닌 인수에는 기본값이 없으므로 클라이언트가 반드시 값을 제공해야 합니다. 기본값은 쿼리를 간결하게 유지하면서 필요할 때 명시적으로 만듭니다.
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!]!
}필수 vs 선택
인수의 ! 접미사가 필수로 만듭니다. 필수 인수를 생략하면 리졸버가 실행되기 전에 검증이 실패하며 명확한 오류를 반환합니다. 진짜 필요한 입력에는 필수를, 조정 가능한 동작에는 기본값이 있는 선택을 권합니다.
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!]!은 널이 아닌 항목들로만 이뤄진 널이 아닌 리스트입니다 — 클라이언트는 리스트를 전달해야 하고 모든 요소가 널이 아니어야 합니다. 깔끔함과 이스케이프 문제 회피를 위해 인라인 리터럴보다 변수로 리스트를 전달하세요.
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"
}변수 타입
변수 타입은 스키마의 인수 타입과 일치해야 합니다. 변수는 널러블, 널 아님, 리스트, 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
}
}기본값
변수 기본값은 클라이언트가 변수를 생략할 때 적용됩니다. 널러블 변수에만 합법입니다 — 널이 아닌 변수는 클라이언트가 반드시 값을 제공해야 한다는 뜻입니다. 기본값으로 클라이언트는 최소 변수 집합만 보내고 서버는 유연하게 유지됩니다.
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.필수 변수
널이 아닌 변수(!)는 필수입니다 — 생략하면 리졸버 실행 전에 검증이 실패합니다. 입력의 존재를 보장하는 가장 안전한 방법입니다. 널이 아닌 변수에는 기본값을 둘 수 없습니다; 기본값을 원하면 변수를 널러블로 만드세요.
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 테스트, 조건부 섹션에 좋습니다 — 하나의 캐시된 쿼리 문서로 모두 처리됩니다.
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
}
}프래그먼트 조합
프래그먼트는 다른 프래그먼트를 펼칠 수 있어 복합 선택을 만듭니다. 이는 필드 선택을 모듈화하고(기본 vs 전체 프로필) UI 컴포넌트가 각자 자신의 데이터 요구를 선언한 뒤 하나의 쿼리로 조합하게 합니다.
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.재사용 프래그먼트
프래그먼트를 렌더링하는 컴포넌트와 함께 두는(colocate) 것은 강력한 패턴입니다: 각 컴포넌트가 자신의 데이터 요구를 선언하고 부모가 이를 하나의 쿼리로 조합합니다. 큰 앱에서 데이터 페칭이 확장됩니다(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에 펼치면 검증 오류입니다. 유니언/인터페이스에 조건부로 펼치려면 타입 조건이 있는 인라인 프래그먼트를 쓰세요. 순환 프래그먼트 펼침도 피하세요.
# 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 접두사가 붙은 이름 없는 선택 집합입니다. 런타임 객체가 타입 조건과 일치할 때만 필드가 적용됩니다. 인터페이스와 유니언에서 타입별 필드에 접근하는 방법입니다.
# 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 문법이 타입 조건입니다. 하나의 선택에서 여러 인라인 프래 그먼트가 유니언/인터페이스의 각 가능한 타입을 개별적으로 처리하게 합니다. 모든 타입이 공유하는 필드는 프래그먼트 밖에서 직접 선택할 수 있습니다.
query Search($term: String!) {
search(term: $term) {
... on User { name email }
... on Post { title author { name } }
... on Comment { body }
}
}유니언 접근
유니언은 __typename 외에는 공유 필드가 없으므로 타입별 데이터를 읽으려면 인라인 프래그먼트가 필수입니다. __typename은 항상 선택 가능하며 각 항목의 구체 타입을 알려줍니다 — 유니언 결과 렌더링에 필수입니다.
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 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 }
}
}타입 조건이 있는 네임드 프래그먼트
네임드 프래그먼트는 자체 타입 조건을 갖습니다. 그래서 유니언/인터페이스 결과에 펼치면 각각 자신이 맞는 타입에만 적용됩니다. 재사용성과 조건부 선택이 결합됩니다 — 유니언의 모든 멤버를 커버하도록 여러 네임드 프래그먼트를 펼치세요.
# 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은 두 개의 내장 클라이언트 디렉티브를 제공합니다: @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로 하나의 쿼리가 여러 모양을 서빙합니다. 불리언 변수를 받으므로, 같은 영속 쿼리가 변수에 따라 요약 뷰나 상세 뷰를 렌더링합니다 — 두 개의 쿼리 문자열을 유지할 필요가 없습니다.
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은 스칼라 타입입니다 — 서브 선택이 없는 리프 값입니다. 마법 문자열 대신 고정 옵션 집합(상태, 역할, 종류)을 갖는 필드에 쓰면 검증과 자기 문서화를 얻습니다.
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은 필드 타입과 인수 타입 양쪽으로 동작합니다. 인수로 쓰이면 클라이언트가 선언된 값 중 하나를 전달합니다. 잘못된 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
}인터페이스
인터페이스 정의
인터페이스는 구현 타 입이 반드시 제공해야 하는 필드 집합을 선언하는 추상 타입입니다. 계약을 정의합니다. 인터페이스는 Node(relay식 전역 ID)나 관련 타입에 걸친 Character 같은 공유 추상화에 유용합니다.
interface Node {
id: ID!
}
interface Character {
name: String!
}
type User implements Node & Character {
id: ID!
name: String!
email: String!
}인터페이스 구현
타입은 implements 키워드로 인터페이스 구현을 선언합니다. 인터페이스가 선언한 모든 필드를 호환되는 타입으로 정의해야 합니다. 타입은 여러 인터페이스(&로 구분)를 구현할 수 있습니다. 스키마가 빌드 시 이를 검증합니다.
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 }
}
}인터페이스 리졸버
인터페이스에는 주어진 런타임 값에 대해 구체 타입 이름(또는 타입 객체)을 반환하는 __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";
},
},
};다중 인터페이스
타입은 & 구분자로 여러 인터페이스를 구현할 수 있습니다. 이는 능력을 조합합니다 — 예: 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 Name = TypeA | TypeB로 정의합니다. 결과가 이질적이지만 개념적으로 관련될 때 유니언이 좋습니다.
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!]!
}유니언 vs 인터페이스
멤버가 공통 계약(모든 멤버가 갖는 필드)을 공유하면 인터페이스를 쓰세요. 멤버가 개념 외에는 관련이 없고 필드를 공유하지 않으면 유니언을 쓰세요. 타입은 많은 유니언에 속할 수 있습니다; 유니언은 다른 유니언을 직접 구현할 수 없습니다.
# 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.유니언 조회
유니언은 자체 필드를 노출하지 않으므로 무엇이든 읽으려면 인라인 프래그먼트가 필요합니다. __typename은 항상 사용 가능하며 각 항목의 구체 타입을 알려줍니다. 유니언에서 타입 조건 없이 필드를 직접 선택하는 것은 검증 오류입니다.
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.유니언 리졸버
인터페이스처럼 유니언에도 런타임 값에 대해 구체 타입 이름을 반환하는 __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;
},
},
};흔한 패턴
유니언은 결과-또는-오류를 모델링합니다: 뮤테이션이 성공 타입과 오류 타입의 유니언을 반환해 클라이언트가 둘 다 처리하게 강제합니다. 선택적 오류 필드가 있는 단일 페이로드보다 타입 안전합니다. (SDL에는 타입 별칭이 아니라 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으로 선언합니다. 관련 필드(사용자, 필터)를 하나의 인수로 묶습니다. 출력 객체 타입과 달리 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 vs Output
출력 타입(type)은 필드 인수와 리졸버를 가질 수 있고, input 타입(input)은 리졸버가 없는 단순 데이터 운반체입니다. 별개의 네임스페이스입니다 — User 타입과 UserInput input을 따로 둘 수 있습니다. 하나를 양쪽에 재사용하지 마세요; 진화가 깨집니다.
# 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이 선택이 됩니다. 기본값은 정적 리터럴이며 요청마다 계산되지 않습니다.
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은 타입과 널 가능성을 검증하지만 의미 규칙(이메 일 형식, 나이 범위, 문자열 길이)은 검증하지 않습니다. 이는 리졸버에서 구현하고 나쁜 데이터에는 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");
}
// ...
}리졸버
리졸버 함수
리졸버는 하나의 필드 값을 만들어내는 함수입니다. 리졸버 맵이 스키마를 미러링합니다: 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),
},
};리졸버 인수
모든 리졸버는 네 개의 인수를 받습니다: parent(부모 필드의 해석된 값), args(이 필드의 인수), context(요청별 공유 객체), info(AST와 실행 메타데이터). 처음 둘이 가장 흔하고, 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),
}리졸버 모범 사례
리졸버는 얇게 유지하세요: 페칭은 컨텍스트의 데이터 소스 클래스에 위임합니다. 이는 데이터 접근을 중앙화하고(테스트 가능, 목킹 가능) 데이터 소스가 배치와 캐싱을 하게 합니다. 리졸버는 조율해야 하며 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.컨텍스트 & DataLoader
컨텍스트 객체
컨텍스트는 연산 안의 모든 리졸버가 공유하는 요청별 객체입니다. 공유 의존성을 여기에 둡니다: 데이터베이스 클라이언트, 인증된 사용자, 데이터 로더, 로거. 컨텍스트 함수는 요청마다 한 번 실행되고 반환 값이 모든 리졸버에 전달됩니다.
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);요청별 컨텍스트
DataLoader 인스턴스는 컨텍스트 함수 안에서 새로 만드세요 — 캐시가 단일 요청으로 스코프됩니다. 로더를 요청 간 재사용하면 캐시된 데이터가 사용자 간에 새어 나옵니다. 컨텍스트 자체가 요청마다 한 번 만들어지므로 요청별 셋업은 여기에 둡니다.
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개 항목의 리스트를 가져온 뒤 항목마다 관계를 로드하는 추가 쿼리를 하나씩 보내는 것입니다. GraphQL의 병렬 필드 해석이 이를 쉽게 유발합니다 — User.posts 리졸버가 사용자마다 실행됩니다. 결과는 쓸데없는 쿼리의 홍수입니다.
# 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는 수많은 개별 로드를 하나의 배치 요청으로 합칩니다. 키 배열을 받아 같은 순서의 결과 배열을 반환하는 배치 함수를 주세요. DataLoader는 하나의 틱 안의 모든 로드를 모아 배치 함수를 한 번 호출합니다.
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)를 쓰세요. 단일 틱 안에서 같은 로더의 모든 로드가 하나의 쿼리로 배치되고, 결과가 요청 기간 동안 캐시됩니다. 리졸버를 단순하게 유지하면서 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는 두 가지를 합니다: 배칭(한 이벤트 루프 틱의 여러 로드가 하나의 배치 호출이 됨)과 키별 캐싱(같은 키의 반복 로드가 같은 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, 쿼리 내 위치, 실패한 필드의 경로, 기계 판독 가능한 코드를 위한 extensions가 있습니다. 필드 오류는 그 필드를 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.커스텀 오류
타입화된 오류 클래스로 의도를 전달하세요: 나쁜 클라이언트 입력(4xx)에는 UserInputError, 인증 누락에는 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는 기계 판독 가능한 데이터를 운반합니다: 안정적인 code 문자열, 재시도 힌트, 검증 필드 경로 등. 클라이언트는 바뀔 수 있는 사람용 메시지를 파싱하지 말고 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입니다(널이 아니면 거슬러 올라감)이고 errors에 나열됩니다. 한 필드의 실패가 전체 응답을 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를 전달해 만들고, 빠른 개발에는 standalone 서버로 시작하세요. 프로덕션에서는 standalone 대신 기존 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를 쓰세요. 미들웨어 장착 전에 서버를 시작합니다. 컨텍스트 함수가 Express의 req/res를 받아 헤더, 세션 읽기나 인증 부착이 가능합니다. GraphQL이 기존 Express 앱에 조립됩니다.
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.컨텍스트 함수
컨텍스트 함수는 요청마다 한 번 실행되며 반환 값이 모든 리졸버에 공유됩니다. 여기서 인증 헤더를 읽고 인증된 사용자, 데이터베이스 클라이언트, 새 DataLoader를 붙이세요. 컨텍스트 안에서 던지면 리졸버 가 실행되기 전에 요청을 거부합니다(예: 잘못된 인증).
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는 요청마다 라이프사이클을 실행합니다: 컨텍스트 빌드 → 쿼리 파싱 → 스키마 검증 → 리졸버 실행 → 응답 포맷. formatError가 오류 모양을 커스터마이징하고, 플러그인이 didResolveOperation, willSendResponse 같은 단계에 훅을 겁니다 — 로깅, 캐싱, 메트릭에 좋습니다.