使用Apollo printSchema生成子图Schema时遇TypeError问题求助
问题原因
你遇到的Cannot read properties of undefined (reading 'kind')错误来自两个关键问题:
- 参数类型不匹配:
buildSubgraphSchema不接受已构建完成的GraphQLSchema实例作为输入——它需要的是SDL字符串、DocumentNode对象,或者包含typeDefs和resolvers的配置对象。直接传入已构建的schema会导致内部处理时解析出错。 - 未定义自定义指令:
@aws_subscribe是AppSync专属的自定义指令,Apollo的默认schema验证规则KnownDirectivesRule无法识别它,必须在schema中显式定义该指令才能通过验证。
解决步骤
1. 显式定义@aws_subscribe指令
在你的schema SDL中添加指令定义:
directive @aws_subscribe(mutations: [String!]!) on FIELD_DEFINITION
2. 修正buildSubgraphSchema的使用方式
如果你已经有一个GraphQLSchema实例,先将其转换为SDL字符串,再拼接指令定义后传入buildSubgraphSchema:
const { printSchema, buildSubgraphSchema } = require('@apollo/subgraph'); // 将现有GraphQLSchema转为SDL const baseSDL = printSchema(schema); // 拼接指令定义与基础SDL const fullSDL = ` directive @aws_subscribe(mutations: [String!]!) on FIELD_DEFINITION ${baseSDL} `; // 构建联邦schema const federatedSchema = buildSubgraphSchema(fullSDL);
如果是从SDL开始构建schema,直接把指令定义包含在原始typeDefs中即可:
const typeDefs = ` directive @aws_subscribe(mutations: [String!]!) on FIELD_DEFINITION type Query { getExample(id: ID!): Example } type Subscription { exampleUpdated: Example @aws_subscribe(mutations: ["updateExample"]) } type Example { id: ID! content: String } `; const resolvers = { // 你的解析器逻辑 }; const federatedSchema = buildSubgraphSchema({ typeDefs, resolvers });
额外排查点
- 检查
@apollo/subgraph和graphql包的版本兼容性,版本不匹配可能引发验证逻辑异常。 - 若你的schema由Graphile Build生成,建议在构建流程中注入指令定义,而非事后修改已生成的
GraphQLSchema实例。
内容的提问来源于stack exchange,提问作者Sivvie Lim
相关产品推荐
相关产品推荐

