graphql-operations

작성자: apollographql

효율적이고 타입 안전한 GraphQL 작업을 작성하고 프래그먼트로 구성하기 위한 모범 사례 가이드입니다. 쿼리, 뮤테이션, 서브스크립션 및 프래그먼트를 다루며, 명명 규칙, 변수 구문, 지시어 사용법을 포함합니다. 핵심 원칙을 강조합니다: 필요한 필드만 요청하고, 모든 작업에 이름을 지정하며, 하드코딩된 값 대신 변수를 사용하고, 캐시 가능성을 위해 id 필드를 포함합니다. 컴포넌트와 함께 프래그먼트를 배치하고 조건부 필드에 @include / @skip 지시어를 사용할 것을 권장합니다...

npx skills add https://github.com/apollographql/skills --skill graphql-operations

GraphQL Operations Guide

This guide covers best practices for writing GraphQL operations (queries, mutations, subscriptions) as a client developer. Well-written operations are efficient, type-safe, and maintainable.

Operation Basics

Query Structure

query GetUser($id: ID!) {
  user(id: $id) {
    id
    name
    email
  }
}

Mutation Structure

mutation CreatePost($input: CreatePostInput!) {
  createPost(input: $input) {
    id
    title
    createdAt
  }
}

Subscription Structure

subscription OnMessageReceived($channelId: ID!) {
  messageReceived(channelId: $channelId) {
    id
    content
    sender {
      id
      name
    }
  }
}

Quick Reference

Operation Naming

PatternExample
QueryGetUser, ListPosts, SearchProducts
MutationCreateUser, UpdatePost, DeleteComment
SubscriptionOnMessageReceived, OnUserStatusChanged

Variable Syntax

# Required variable
query GetUser($id: ID!) { ... }

# Optional variable with default
query ListPosts($first: Int = 20) { ... }

# Multiple variables
query SearchPosts($query: String!, $status: PostStatus, $first: Int = 10) { ... }

Fragment Syntax

# Define fragment
fragment UserBasicInfo on User {
  id
  name
  avatarUrl
}

# Use fragment
query GetUser($id: ID!) {
  user(id: $id) {
    ...UserBasicInfo
    email
  }
}

Directives

query GetUser($id: ID!, $includeEmail: Boolean!) {
  user(id: $id) {
    id
    name
    email @include(if: $includeEmail)
  }
}

query GetPosts($skipDrafts: Boolean!) {
  posts {
    id
    title
    draft @skip(if: $skipDrafts)
  }
}

Key Principles

1. Request Only What You Need

# Good: Specific fields
query GetUserName($id: ID!) {
  user(id: $id) {
    id
    name
  }
}

# Avoid: Over-fetching
query GetUser($id: ID!) {
  user(id: $id) {
    id
    name
    email
    bio
    posts {
      id
      title
      content
      comments {
        id
      }
    }
    followers {
      id
      name
    }
    # ... many unused fields
  }
}

2. Name All Operations

# Good: Named operation
query GetUserPosts($userId: ID!) {
  user(id: $userId) {
    posts {
      id
      title
    }
  }
}

# Avoid: Anonymous operation
query {
  user(id: "123") {
    posts {
      id
      title
    }
  }
}

3. Use Variables, Not Inline Values

# Good: Variables
query GetUser($id: ID!) {
  user(id: $id) {
    id
    name
  }
}

# Avoid: Hardcoded values
query {
  user(id: "123") {
    id
    name
  }
}

4. Colocate Fragments with Components

// UserAvatar.tsx
export const USER_AVATAR_FRAGMENT = gql`
  fragment UserAvatar on User {
    id
    name
    avatarUrl
  }
`;

function UserAvatar({ user }) {
  return <img src={user.avatarUrl} alt={user.name} />;
}

Reference Files

Detailed documentation for specific topics:

  • Queries - Query patterns and optimization
  • Mutations - Mutation patterns and error handling
  • Fragments - Fragment organization and reuse
  • Variables - Variable usage and types
  • Tooling - Code generation and linting

Ground Rules

  • ALWAYS name your operations (no anonymous queries/mutations)
  • ALWAYS use variables for dynamic values
  • ALWAYS request only the fields you need
  • ALWAYS include id field for cacheable types
  • NEVER hardcode values in operations
  • NEVER duplicate field selections across files
  • PREFER fragments for reusable field selections
  • PREFER colocating fragments with components
  • USE descriptive operation names that reflect purpose
  • USE @include/@skip for conditional fields

apollographql의 다른 스킬

apollo-client
apollographql
Apollo Client는 로컬 및 원격 데이터를 GraphQL로 관리할 수 있게 해주는 JavaScript용 종합 상태 관리 라이브러리입니다. 버전 4.x는 개선된 캐싱, 더 나은 TypeScript 지원, React 19 호환성을 제공합니다.
official
apollo-client
apollographql
Apollo Client 4.x를 사용하여 React 애플리케이션을 구축하기 위한 종합 가이드로, 쿼리, 뮤테이션, 캐싱 및 상태 관리를 다룹니다. 여러 React 프레임워크 및 설정을 지원합니다: 클라이언트 측 앱(Vite, CRA), React Server Components를 사용하는 Next.js App Router, 스트리밍 SSR을 지원하는 React Router 7, TanStack Start. 쿼리(useQuery, useLazyQuery), 뮤테이션(useMutation)을 위한 훅과 최신 React 18+ 및 19를 위한 Suspense 기반 패턴(useSuspenseQuery, useBackgroundQuery)을 포함합니다.
official
apollo-connectors
apollographql
REST API를 @source 및 @connect 지시문을 사용하여 GraphQL 슈퍼그래프에 통합합니다. 구조화된 5단계 프로세스를 제공합니다: API 구조 조사, 지시문으로 스키마 구현, rover supergraph compose를 통한 검증, 커넥터 실행, 테스트 커버리지. 헤더, 본문 페이로드, N+1 패턴을 위한 배칭, $env를 통한 환경 변수 주입을 포함한 요청 구성을 지원합니다. 필드 선택, 별칭, 중첩 데이터를 위한 하위 선택, 엔티티...를 포함한 응답 매핑을 처리합니다.
official
apollo-federation
apollographql
Apollo Federation은 여러 GraphQL API(서브그래프)를 하나의 통합된 슈퍼그래프로 구성할 수 있게 해줍니다.
official
apollo-ios
apollographql
Apollo iOS는 Apple 플랫폼을 위한 강력한 타입의 GraphQL 클라이언트입니다. GraphQL 작업과 스키마에서 Swift 타입을 생성하며, async/await 클라이언트, 정규화된 캐시(인메모리 또는 SQLite 기반), 쿼리, 뮤테이션 및 멀티파트 구독을 처리하는 플러그형 인터셉터 기반 HTTP 전송, 그리고 모든 작업 유형을 전달할 수 있는 선택적 WebSocket 전송(graphql-transport-ws)을 제공합니다.
official
apollo-kotlin
apollographql
Apollo Kotlin은 GraphQL 연산과 스키마에서 Kotlin 모델을 생성하는 강력한 타입의 GraphQL 클라이언트로, Android, JVM 및 Kotlin Multiplatform 프로젝트에서 사용할 수 있습니다.
official
apollo-mcp-server
apollographql
AI 에이전트를 GraphQL API에 연결하여 Model Context Protocol을 통해 내장된 인트로스펙션 및 작업 도구를 제공합니다. GraphQL 작업을 MCP 도구로 노출하며, 로컬 파일, GraphOS Studio 컬렉션, 지속적 쿼리 매니페스트의 세 가지 작업 소스를 지원합니다. 스키마 탐색 및 임시 쿼리 테스트를 위한 네 가지 인트로스펙션 도구(introspect, search, validate, execute)를 제공하며, 축약 표기법을 사용한 미니피케이션 모드로 토큰 사용량을 줄입니다. 정적 헤더를 통한 구성 가능한 인증,...
official
apollo-router
apollographql
Apollo Router는 Apollo Federation 2 슈퍼그래프를 실행하기 위해 Rust로 작성된 고성능 그래프 라우터입니다. 서브그래프 앞에 위치하여 쿼리 계획, 실행 및 응답 구성을 처리합니다.
official