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 是一個全面的 JavaScript 狀態管理庫,讓您能透過 GraphQL 管理本地與遠端資料。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)的鉤子,以及基於 Suspense 的模式(useSuspenseQuery、useBackgroundQuery),適用於現代 React 18+ 與 19...
official
apollo-connectors
apollographql
使用@source和@connect指令將REST API整合至GraphQL超級圖譜。提供結構化五步驟流程:研究API結構、使用指令實作綱要、透過rover supergraph compose驗證、執行連接器、測試覆蓋範圍。支援請求配置,包含標頭、請求主體、N+1模式批次處理,以及透過$env注入環境變數。處理回應映射,包含欄位選取、別名、巢狀資料子選取及實體...
official
apollo-federation
apollographql
Apollo Federation 可將多個 GraphQL API(子圖)組合成統一的超級圖表。
official
apollo-ios
apollographql
Apollo iOS 是一個專為 Apple 平台設計的強型別 GraphQL 客戶端。它能從你的 GraphQL 操作與 schema 生成 Swift 型別,並提供 async/await 客戶端、正規化快取(記憶體或 SQLite 支援)、可插拔的攔截器式 HTTP 傳輸(處理查詢、變更與多部分訂閱),以及可選的 WebSocket 傳輸(graphql-transport-ws),可承載任何操作類型。
official
apollo-kotlin
apollographql
Apollo Kotlin 是一個強型別的 GraphQL 客戶端,能從你的 GraphQL 操作和綱要中生成 Kotlin 模型,可用於 Android、JVM 和 Kotlin Multiplatform 專案。
official
apollo-mcp-server
apollographql
透過模型上下文協定將AI代理連接至GraphQL API,內建內省與操作工具。將GraphQL操作暴露為MCP工具;支援三種操作來源:本地檔案、GraphOS Studio集合與持久化查詢清單。提供四種內省工具(introspect、search、validate、execute)用於結構探索與臨時查詢測試;壓縮模式透過簡潔標記減少Token用量。可透過靜態標頭設定認證...
official
apollo-router
apollographql
Apollo Router 是一款以 Rust 編寫的高效能圖形路由器,用於執行 Apollo Federation 2 超級圖。它位於子圖前端,負責查詢規劃、執行與回應組合。
official