关于 apollo-federation
apollo-federation 是编写 Apollo Federation 2 GraphQL 模式的参考技能,面向将多个子图组合为 supergraph 的开发者,介绍指令和常见模式。
主要功能
- 01使用 @link 配置 Federation 2
- 02核心指令语法与用途
- 03实体及子图贡献模式
- 04使用 @requires 定义计算字段
- 05本地组合与生产环境检查
适用场景
- 01在多个子图中定义实体
- 02添加依赖外部字段的字段
- 03在子图间共享值类型
- 04验证 supergraph 组合
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ apollographql/ skills --skill apollo-federation安装后在 Claude Code 中输入/apollo-federation确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/composition.mddirectives.mdschema-patterns.md详细介绍
Apollo Federation 模式编写
Apollo Federation 支持将多个 GraphQL API(子图)组合成一个统一的超图。
Federation 2 模式设置
每个 Federation 2 子图都必须通过 @link 选择启用:
extend schema
@link(url: "https://specs.apollo.dev/federation/v2.12",
import: ["@key", "@shareable", "@external", "@requires", "@provides"])
只导入子图实际使用的指令。这里展示的版本(v2.12)仅供参考——照抄之前,请查看 Federation 更新日志,了解当前支持的版本。
子图的
@link版本是一个最低版本要求,而不是组合版本——完整说明请参阅 Federation 版本。
核心指令速查
| 指令 | 用途 | 示例 |
|---|---|---|
@key | 定义带有唯一键的实体 | type Product @key(fields: "id") |
@shareable | 允许多个子图解析字段 | type Position @shareable { x: Int! } |
@external | 引用另一个子图中的字段 | weight: Int @external |
@requires | 定义依赖外部字段的计算字段 | shippingCost: Int @requires(fields: "weight") |
@provides | 有条件地解析外部字段 | @provides(fields: "name") |
@override | 将字段迁移到此子图 | @override(from: "Products") |
@inaccessible | 从 API 模式中隐藏 | internalId: ID! @inaccessible |
@interfaceObject | 向实体接口添加字段 | type Media @interfaceObject |
参考文件
特定主题的详细文档:
核心范式
实体定义
type Product @key(fields: "id") {
id: ID!
name: String!
price: Int
}
跨子图贡献实体
# Products subgraph
type Product @key(fields: "id") {
id: ID!
name: String!
price: Int
}
# Reviews subgraph
type Product @key(fields: "id") {
id: ID!
reviews: [Review!]!
averageRating: Float
}
使用 @requires 的计算字段
type Product @key(fields: "id") {
id: ID!
size: Int @external
weight: Int @external
shippingEstimate: String @requires(fields: "size weight")
}
使用 @shareable 的值类型
type Money @shareable {
amount: Int!
currency: String!
}
实体存根(引用但不贡献)
type Product @key(fields: "id", resolvable: false) {
id: ID!
}
基本规则
- 始终使用带有
@link指令的 Federation 2.x 语法 - 始终只导入子图实际使用的指令
- 切勿使用
@shareable,除非确保所有子图对该字段都返回相同的值 - 对于简单的实体标识,优先使用包含单个 ID 字段的
@key - 使用
rover supergraph compose在本地验证组合 - 使用
rover subgraph check根据生产超图进行验证
评论
支持 Markdown