You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

添加@key指令后启动NestJS联邦Property服务报GraphQLError求助

解决联邦Property服务启动报错:GraphQLError: Type Property must define one or more fields.

问题核心

给Property模型添加@Directive('@key(fields: "id")')注解后,启动联邦服务触发上述错误,但自动生成的Schema中Property明明包含多个字段。

问题原因

  1. 依赖包冲突:同时安装了@apollo/federation(联邦1.x包)和@apollo/subgraph(联邦2.x包),两者在指令处理逻辑上不兼容,导致联邦服务解析Schema时出现异常。
  2. GraphQL模块未配置为子图模式:NestJS的Apollo模块默认不是子图模式,未明确指定驱动时,无法正确解析联邦2的@key指令。

解决方案

步骤1:清理冲突依赖

修改package.json,移除@apollo/federation依赖,仅保留@apollo/subgraph:

{
  "dependencies": {
    // 移除 "@apollo/federation": "^0.38.1",
    "@apollo/subgraph": "^2.2.2",
    // 其余依赖保持不变
  }
}

执行命令更新依赖:

npm install

步骤2:配置GraphQL模块为子图模式

在AppModule中修改GraphQL配置,指定使用ApolloSubgraphDriver:

import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloSubgraphDriver, ApolloSubgraphDriverConfig } from '@nestjs/apollo';
import { join } from 'path';
import { PropertiesModule } from './properties/properties.module';

@Module({
  imports: [
    GraphQLModule.forRoot<ApolloSubgraphDriverConfig>({
      driver: ApolloSubgraphDriver,
      autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
      sortSchema: true,
    }),
    PropertiesModule,
  ],
})
export class AppModule {}

步骤3:验证模型注解(可选)

确认Property模型的@Directive语法无误,当前写法合规:

@ObjectType()
@Directive('@key(fields: "id")')
export class Property {
  @Field(() => ID)
  id: string;

  // 其余字段保持不变
}

步骤4:重启服务

清理构建缓存后启动开发服务:

npm run prebuild && npm run start:dev

验证结果

重新启动后,自动生成的Schema中Property类型会正确带上@key指令:

type Property @key(fields: "id") {
  id: ID!
  owner: String!
  propertyUPRN: String!
  address: Address!
}

此时服务可正常启动,不再出现字段缺失的报错。

内容的提问来源于stack exchange,提问作者farmlandbee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 23:25:18