新版Apollo与GraphQL tools远程schema拼接报Query root type错误
触发原因
- 你使用的
@graphql-tools/stitch v8版本对远程子schema的配置要求更新:仅给subschemas传递schema字段时,工具会将其识别为本地静态schema,无法正确提取合并两个远程schema的根Query类型,最终生成的gatewaySchema缺失Query根类型,而Apollo Server要求所有挂载的schema必须存在Query根类型,因此抛出错误。 - 另一个可能的触发原因是两个远程schema的Query类型存在重名字段,未配置合并规则导致stitch工具无法生成合法的Query根类型;也有可能是远程schema加载失败(如环境变量配置错误、token无效、网络不通),得到的schema本身就没有Query类型。
解决方案
- 先验证远程schema是否加载正常
在loadSchema执行后添加日志输出,确认加载到的schema存在Query根类型:
console.log('Shopify schema query type:', shopifySchema.getQueryType()) console.log('Contentful schema query type:', contentfulSchema.getQueryType())
如果输出为null,检查环境变量路径、API token权限、网络连通性即可。
- 修正subschemas配置,添加executor
远程子schema需要配置对应executor才能被stitch工具正确识别合并,修改代码如下:
首先导入依赖:
import { buildHTTPExecutor } from '@graphql-tools/executor-http';
然后为两个远程服务创建executor:
// 在加载完两个schema之后添加 const shopifyExecutor = buildHTTPExecutor({ endpoint: process.env.SHOPIFY_STOREFRONT_URL, headers: { "X-Shopify-Storefront-Access-Token": process.env.SHOPIFY_STOREFRONT_API_TOKEN, }, fetch }); const contentfulExecutor = buildHTTPExecutor({ endpoint: process.env.CONTENTFUL_API_URL, headers: { Authorization: `Bearer ${process.env.CONTENTFUL_API_TOKEN}`, }, fetch });
修改stitchSchemas配置:
const gatewaySchema = stitchSchemas({ subschemas: [ { schema: shopifySchema, executor: shopifyExecutor }, { schema: contentfulSchema, executor: contentfulExecutor } ], // 可选:如果存在同名类型冲突,开启合并 mergeTypes: true, // 可选:强制声明根Query,避免完全无字段时Query被丢弃 typeDefs: ` extend type Query { _placeholder: String } ` });
- 如果是因为两个schema的Query字段重名冲突导致的问题,添加对应的字段合并规则即可,以常见的
node字段冲突为例:
const gatewaySchema = stitchSchemas({ subschemas: [/* 同上 */], merge: { Query: { fields: { node: { // 配置字段的查询路由规则,根据实际需求调整 selectionSet: '{ id }', resolve: (obj, args, context, info) => { // 按需路由到对应subschema执行 } } } } } })
内容的提问来源于stack exchange,提问作者Lorenzo Rivosecchi
相关产品推荐
相关产品推荐

