apollo-router-plugin-creator

作成者: apollographql

Apollo Router用のネイティブRustプラグインを作成します。

npx skills add https://github.com/apollographql/skills --skill apollo-router-plugin-creator

Apollo Router Plugin Creator

Create native Rust plugins for Apollo Router.

Request Lifecycle

┌────────┐             ┌────────────────┐                                   ┌────────────────────┐               ┌───────────────────┐       ┌─────────────────────┐
│ Client │             │ Router Service │                                   │ Supergraph Service │               │ Execution Service │       │ Subgraph Service(s) │
└────┬───┘             └────────┬───────┘                                   └──────────┬─────────┘               └─────────┬─────────┘       └──────────┬──────────┘
     │                          │                                                      │                                   │                            │
     │      Sends request       │                                                      │                                   │                            │
     │──────────────────────────▶                                                      │                                   │                            │
     │                          │                                                      │                                   │                            │
     │                          │  Converts raw HTTP request to GraphQL/JSON request   │                                   │                            │
     │                          │──────────────────────────────────────────────────────▶                                   │                            │
     │                          │                                                      │                                   │                            │
     │                          │                                                      │  Initiates query plan execution   │                            │
     │                          │                                                      │───────────────────────────────────▶                            │
     │                          │                                                      │                                   │                            │
     │                          │                                                      │                               ┌par [Initiates sub-operation]───────┐
     │                          │                                                      │                               │   │                            │   │
     │                          │                                                      │                               │   │  Initiates sub-operation   │   │
     │                          │                                                      │                               │   │────────────────────────────▶   │
     │                          │                                                      │                               │   │                            │   │
     │                          │                                                      │                               ├[Initiates sub-operation]╌╌╌╌╌╌╌╌╌╌╌┤
     │                          │                                                      │                               │   │                            │   │
     │                          │                                                      │                               │   │  Initiates sub-operation   │   │
     │                          │                                                      │                               │   │────────────────────────────▶   │
     │                          │                                                      │                               │   │                            │   │
     │                          │                                                      │                               ├[Initiates sub-operation]╌╌╌╌╌╌╌╌╌╌╌┤
     │                          │                                                      │                               │   │                            │   │
     │                          │                                                      │                               │   │  Initiates sub-operation   │   │
     │                          │                                                      │                               │   │────────────────────────────▶   │
     │                          │                                                      │                               │   │                            │   │
     │                          │                                                      │                               └────────────────────────────────────┘
     │                          │                                                      │                                   │                            │
     │                          │                                                      │  Assembles and returns response   │                            │
     │                          │                                                      ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│                            │
     │                          │                                                      │                                   │                            │
     │                          │            Returns GraphQL/JSON response             │                                   │                            │
     │                          ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│                                   │                            │
     │                          │                                                      │                                   │                            │
     │  Returns HTTP response   │                                                      │                                   │                            │
     ◀╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌│                                                      │                                   │                            │
     │                          │                                                      │                                   │                            │
┌────┴───┐             ┌────────┴───────┐                                   ┌──────────┴─────────┐               ┌─────────┴─────────┐       ┌──────────┴──────────┐
│ Client │             │ Router Service │                                   │ Supergraph Service │               │ Execution Service │       │ Subgraph Service(s) │
└────────┘             └────────────────┘                                   └────────────────────┘               └───────────────────┘       └─────────────────────┘

Service Hooks

Service Overview

ServiceDescription
router_serviceRuns at the very beginning and very end of the HTTP request lifecycle.For example, JWT authentication is performed within the RouterService.Define router_service if your customization needs to interact with HTTP context and headers. It doesn't support access to the body property
supergraph_serviceRuns at the very beginning and very end of the GraphQL request lifecycle.Define supergraph_service if your customization needs to interact with the GraphQL request or the GraphQL response. For example, you can add a check for anonymous queries.
execution_serviceHandles initiating the execution of a query plan after it's been generated.Define execution_service if your customization includes logic to govern execution (for example, if you want to block a particular query based on a policy decision).
subgraph_serviceHandles communication between the router and your subgraphs.Define subgraph_service to configure this communication (for example, to dynamically add HTTP headers to pass to a subgraph).Whereas other services are called once per client request, this service is called once per subgraph request that's required to resolve the client's request. Each call is passed a subgraph parameter that indicates the name of the corresponding subgraph.

Signatures:

fn router_service(&self, service: router::BoxService) -> router::BoxService
fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService
fn execution_service(&self, service: execution::BoxService) -> execution::BoxService
fn subgraph_service(&self, name: &str, service: subgraph::BoxService) -> subgraph::BoxService

Individual Hooks (Tower Layers)

Use ServiceBuilder to compose these hooks within any service:

HookPurposeSync/Async
map_request(fn)Transform request before proceedingSync
map_response(fn)Transform response before returningSync
checkpoint(fn)Validate/filter, can short-circuitSync
checkpoint_async(fn)Async validation, can short-circuitAsync
buffered()Enable service cloning (needed for async)-
instrument(span)Add tracing span around service-
rate_limit(num, period)Control request throughput-
timeout(duration)Set operation time limit-

Choosing a Service Hook

By data needed:

  • HTTP headers only → router_service
  • GraphQL query/variables → supergraph_service
  • Query plan → execution_service
  • Per-subgraph control → subgraph_service

By timing:

  • Before GraphQL parsing → router_service request
  • After parsing, before planning → supergraph_service request
  • After planning, before execution → execution_service request
  • Before/after each subgraph call → subgraph_service
  • Final response to client → router_service response

See references/service-hooks.md for implementation patterns.

Quick Start

Step 1: Create Plugin File

Create a new file src/plugins/my_plugin.rs with required imports:

use std::ops::ControlFlow;
use apollo_router::plugin::{Plugin, PluginInit};
use apollo_router::register_plugin;
use apollo_router::services::{router, subgraph, supergraph};
use schemars::JsonSchema;
use serde::Deserialize;
use tower::{BoxError, ServiceBuilder, ServiceExt};

const PLUGIN_NAME: &str = "my_plugin";

Step 2: Define Configuration Struct

Every plugin needs a configuration struct with Deserialize and JsonSchema derives. The JsonSchema enables configuration validation in editors:

#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]
struct MyPluginConfig {
  /// Enable the plugin
  enabled: bool,
  // Add other configuration fields as needed
}

Step 3: Define Plugin Struct

#[derive(Debug)]
struct MyPlugin {
  configuration: MyPluginConfig,
}

Step 4: Implement Plugin Trait

Implement the Plugin trait with the required Config type and new constructor:

#[async_trait::async_trait]
impl Plugin for MyPlugin {
  type Config = MyPluginConfig;

  async fn new(init: PluginInit<Self::Config>) -> Result<Self, BoxError> {
    Ok(MyPlugin { configuration: init.config })
  }

  // Add service hooks based on your needs (see "Choosing a Service Hook" section)
}

Step 5: Add Service Hooks

Choose which service(s) to hook based on your requirements, see Service Overview for details.

Example service hook:

fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService {
  if !self.configuration.enabled {
    return service;
  }

  ServiceBuilder::new()
    .map_request(|req| { /* transform request */ req })
    .map_response(|res| { /* transform response */ res })
    .service(service)
    .boxed()
}

Step 6: Register Plugin

At the bottom of your plugin file, register it with the router:

register_plugin!("acme", "my_plugin", MyPlugin);

Step 7: Add Module to mod.rs

In src/plugins/mod.rs, add your module:

pub mod my_plugin;

Step 8: Configure in YAML

Enable your plugin in the router configuration:

plugins:
  acme.my_plugin:
    enabled: true

Common Patterns

For implementation patterns and code examples, see references/service-hooks.md:

  • Enable/disable pattern
  • Request/response transformation (map_request, map_response)
  • Checkpoint (early return/short-circuit)
  • Context passing between hooks
  • Async operations (checkpoint_async, buffered)
  • Error response builders

Examples

Apollo Router Examples

Located in the Apollo Router plugins directory:

PluginService HookPatternDescription
forbid_mutations.rsexecution_servicecheckpointSimple gate on query plan
expose_query_plan.rsexecution + supergraphContext passingMulti-service coordination
cors.rsrouter_serviceHTTP layerCORS handling at HTTP level
headers/subgraph_serviceLayer compositionComplex header manipulation

For full code examples and testing patterns, see references/examples.md.

Prerequisites

It is advised to have the rust-best-practices skill installed for writing idiomatic Rust code when developing router plugins. If installed, follow those best practices when generating or modifying plugin code.

Resources

apollographqlのその他のスキル

apollo-client
apollographql
Apollo Clientは、GraphQLを使用してローカルデータとリモートデータの両方を管理できる、JavaScript向けの包括的な状態管理ライブラリです。バージョン4.xでは、キャッシュの改善、TypeScriptサポートの強化、React 19との互換性がもたらされています。
official
apollo-client
apollographql
We need to translate the given text from English to Japanese. The text is a description of an agent skill for apollo-client. We must preserve the name "apollo-client" if it appears, but it does not appear in the text. The text mentions "Apollo Client 4.x" - that should be preserved as is. Also preserve technical terms like useQuery, useLazyQuery, useMutation, useSuspenseQuery, useBackgroundQuery, Vite, CRA, Next.js App Router, React Server Components, React Router 7, streaming SSR, TanStack Start, React 18+, 19. Also preserve numbers and URLs (none here). Do not add any extra commentary or labels. Just translate the text. The text: "Comprehensive guide for building React applications with Apollo Client 4.x, covering queries, mutations, caching, and state management. Supports multiple React frameworks and setups: client-side apps (Vite, CRA), Next.js App Router with React Server Components, React Router 7 with streaming SSR, and TanStack Start Includes hooks
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
Model Context Protocolを通じてAIエージェントをGraphQL APIに接続し、内蔵のイントロスペクションおよび操作ツールを提供します。GraphQL操作をMCPツールとして公開し、ローカルファイル、GraphOS Studioコレクション、永続化クエリマニフェストの3つの操作ソースをサポートします。スキーマ探索やアドホッククエリテストのための4つのイントロスペクションツール(introspect、search、validate、execute)を提供し、ミニフィケーションモードではコンパクトな表記でトークン使用量を削減します。静的ヘッダーを介した設定可能な認証、...
official
apollo-router
apollographql
Apollo Routerは、Apollo Federation 2のスーパーグラフを実行するためにRustで書かれた高性能なグラフルーターです。サブグラフの前に配置され、クエリの計画、実行、レスポンスの合成を処理します。
official