如何让Apollo Federation Rover连接本地端点并解决400错误?
解决Rover合成联邦子图时的400 Bad Request错误
问题根源
你的Apollo Server是普通GraphQL服务器,未配置为联邦子图服务器。Rover执行supergraph compose时,会向子图端点发送联邦专属的__SDL查询以获取子图Schema,普通服务器无法识别该请求,因此返回400错误。
解决步骤
1. 安装联邦子图依赖
在项目中安装@apollo/subgraph,用于将普通Apollo Server转换为联邦子图服务器:
npm install @apollo/subgraph
2. 修改Apollo Server代码
调整代码以支持联邦规范:
- 导入联邦Schema构建工具
- 为Schema添加联邦指令(如
@key,标识子图中的共享实体) - 添加实体引用解析器(联邦子图必备)
修改后的完整代码:
import { ApolloServer } from '@apollo/server'; import { startStandaloneServer } from '@apollo/server/standalone'; import { buildSubgraphSchema } from '@apollo/subgraph'; import { dateScalar } from './scalar'; const books = [ { title: 'The Awakening', author: 'Kate Chopin', }, { title: 'City of Glass', author: 'Paul Auster', }, ]; // 为Book类型添加@key联邦指令 const typeDefs = `#graphql scalar AWSDateTime type Book @key(fields: "title") { title: String author: String } type Query { books: [Book] } `; const resolvers = { Query: { books: () => books, }, AWSDateTime: dateScalar, // 新增实体引用解析器,处理跨子图的实体查询 Book: { __resolveReference(book) { return books.find(b => b.title === book.title); } } }; const startServer = async () => { // 使用buildSubgraphSchema构建符合联邦规范的Schema const server = new ApolloServer({ schema: buildSubgraphSchema({ typeDefs, resolvers }), }); const { url } = await startStandaloneServer(server, { listen: { port: 4000 }, }); console.log(`🚀 Server ready at: ${url}`); }; startServer();
3. 验证Rover配置
确保配置文件中的subgraph_url指向正确的端点(默认是http://localhost:4000/graphql):
federation_version: 2 subgraphs: test: routing_url: http://localhost:4000/ schema: subgraph_url: http://localhost:4000/graphql
4. 重新执行合成命令
重启你的Apollo Server,然后运行:
rover supergraph compose --config ./supergraph.yaml
关键说明
- 联邦子图必须包含至少一个带
@key指令的实体类型,用于在超级图中标识跨子图共享的数据。 __resolveReference解析器是联邦子图的核心组件,负责处理其他子图对当前子图实体的引用请求。- Rover通过
__SDL查询获取子图Schema,只有联邦子图服务器会响应该请求。
内容的提问来源于stack exchange,提问作者Joey Yi Zhao
相关产品推荐
相关产品推荐

