什么是 Code First 模式?如何使用 @ObjectType、@Field 等装饰器定义 GraphQL 类型?

解读

国内大厂后端面试中,GraphQL 选型已从“要不要用”过渡到“怎么用”。Code First 是 NestJS 官方推荐的 GraphQL 开发范式,核心思想是:先写 TypeScript 实体,再由框架在运行时自动生成 SDL(Schema Definition Language)。面试官问这道题,想确认三件事:

  1. 你是否理解 Code First 与 Schema First 的本质差异;
  2. 能否熟练用装饰器把 TypeScript 类型映射成 GraphQL 类型;
  3. 是否知道装饰器背后的元数据如何被 IoC 容器消费,从而支撑反射生成 SDL。
    回答时务必结合企业级落地细节:字段权限、复杂类型、联合类型、分页、自定义 Scalar、热更新、多语言错误提示等,否则会被认为“只会写玩具代码”。

知识点

  1. Code First vs Schema First:前者“类即 Schema”,后者“SDL 即真理”;国内项目迭代快,Code First 可随 CI/CD 自动生成版本化 Schema,减少协议漂移。
  2. @ObjectType:标记一个 TS 类为 GraphQL Object Type,可设置 name、description、implements 接口。
  3. @Field:标记类属性为 GraphQL 字段,支持 type 函数、 nullable、description、complexity、deprecationReason;对数组必须写成 () => [Int] 否则反射拿不到泛型。
  4. 复杂类型:@ObjectType 可嵌套 @ObjectType;@Field 支持自定义 Scalar(如 Date、JSON、BigInt)与 Enum;联合类型用 @Field(() => GraphQLUnionType) 并配合 createUnionType。
  5. 权限与暴露控制:字段级 @UseGuards、@Directive('@auth(role: ADMIN)');敏感字段加 @Field({ nullable: true }) 并在 resolver 层做权限过滤,防止过度查询。
  6. 元数据与反射:底层依赖 reflect-metadata,编译后生成 design:type、design:paramtypes、design:returntype;NestJS 在 GraphQLDefinitionsFactory 阶段读取元数据生成 SDL 并写入 .graphql 文件,可做静态检查。
  7. 热更新与多服务:微服务场景下,每个子域独立生成子 Schema,Apollo Federation 2 通过 @key、@shareable 聚合;国内常用 Nx Monorepo + graphql-codegen 做子域版本对齐。
  8. 性能:字段级 complexity 插件防深查询;@FieldResolver 配合 DataLoader 做 N+1 治理;阿里云函数计算场景下,关闭 introspection 并做 Schema 裁剪,减少冷启动耗时。

答案

Code First 模式是 NestJS 借助 TypeScript 装饰器与反射元数据,在运行时把类定义自动转换成 GraphQL Schema 的开发范式。与先写 SDL 的 Schema First 相比,Code First 把“协议”与“实现”收拢到同一份代码,天然享受类型检查、重构提示与单测覆盖率,适合国内互联网快速迭代节奏。

定义 GraphQL 类型的最小闭环分三步:

第一步,声明实体并开启装饰器:

import { ObjectType, Field, ID, Int, Float, registerEnumType } from '@nestjs/graphql';

enum Episode {
  NEWHOPE = 4,
  EMPIRE = 5,
  JEDI = 6,
}
registerEnumType(Episode, { name: 'Episode', description: '星球大战三部曲' });

@ObjectType({ description: '电影角色' })
export class Character {
  @Field(() => ID)
  id: string;

  @Field({ description: '姓名' })
  name: string;

  @Field(() => Int, { nullable: true, complexity: 5 })
  age?: number;

  @Field(() => Float)
  height: number;

  @Field(() => [Episode])
  appearsIn: Episode[];

  /* 敏感字段:仅管理员可见 */
  @Field({ nullable: true })
  phone?: string;
}

第二步,在 Resolver 中消费:

@Resolver(() => Character)
export class CharacterResolver {
  constructor(private svc: CharacterService) {}

  @Query(() => Character, { name: 'character' })
  @UseGuards(JwtAuthGuard, RoleGuard)
  async getCharacter(
    @Args('id', { type: () => ID }) id: string,
    @CurrentUser() user: User,
  ) {
    const entity = await this.svc.findOne(id);
    /* 字段级脱敏 */
    if (!user.hasRole('ADMIN')) entity.phone = null;
    return entity;
  }

  @ResolveField('friends', () => [Character])
  async getFriends(@Parent() character: Character) {
    return this.svc.loadFriends(character.id);
  }
}

第三步,在 GraphQLModule.forRoot<ApolloDriverConfig> 中开启自动 Schema 生成:

GraphQLModule.forRoot<ApolloDriverConfig>({
  driver: ApolloDriver,
  autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
  buildSchemaOptions: {
    dateScalarMode: 'timestamp',
    numberScalarMode: 'integer',
    orphanedTypes: [SomeRareType], // 防止 tree-shaking 误删
  },
  introspection: process.env.NODE_ENV !== 'production',
  plugins: [complexityPlugin({ maxComplexity: 1000 })],
}),

至此,运行 npm run start:dev,框架会读取所有 @ObjectType 与 @Field 装饰器,结合反射元数据生成标准 SDL 并输出到 schema.gql,同时自动注册 Scalar、Enum、Union、Input、Args 等类型,无需手写一行 SDL。

拓展思考

  1. 国内金融场景要求“字段级脱敏”与“审计日志”,可在 @Field 上自定义 @AuditLog 装饰器,结合 AOP 拦截器在 GqlExecutionContext 中统一记录旧值与新值,实现合规。
  2. 当团队规模>50 人,Schema 冲突概率陡增,可在 Nx Monorepo 里为每个子域建立 *.graphqls 的“只读快照”,CI 阶段用 graphql-inspector 做 Breaking Change 检测,防止上线炸库。
  3. 对 Serverless 场景,冷启动耗时敏感,可关闭 autoSchemaFile 生成,改为 buildSchemaOptions.autoSchemaFile: false,在构建阶段用 GraphQLSchemaBuilder 预生成 Schema 并序列化成 JSON,运行时直接 loadSchemaSync,缩短 200~300 ms。
  4. 复杂查询常出现“N+1”与“深查询”问题,可结合 @FieldResolver + DataLoader + 字段级 complexity 做两层防护;再使用阿里 SLS 日志分析 Top 查询,动态调整 maxComplexity 阈值,实现智能流控。