NestJS中文文档
GraphQL / 生成 SDL
已译 191/191

生成 SDL

警告

本章仅适用于代码优先方式。

如需手动生成 GraphQL SDL schema(即不运行应用、不连接数据库、不挂接解析器等),请使用 GraphQLSchemaBuilderModule:

async function generateSchema() {
  const app = await NestFactory.create(GraphQLSchemaBuilderModule);
  await app.init();

  const gqlSchemaFactory = app.get(GraphQLSchemaFactory);
  const schema = await gqlSchemaFactory.create([RecipesResolver]);
  console.log(printSchema(schema));
}
提示

GraphQLSchemaBuilderModule 和 GraphQLSchemaFactory 从 @nestjs/graphql 包导入,printSchema 函数从 graphql 包导入。

用法

gqlSchemaFactory.create() 方法接收一个解析器类引用的数组。例如:

const schema = await gqlSchemaFactory.create([
  RecipesResolver,
  AuthorsResolver,
  PostsResolver,
]);

它还接受一个可选的第二个参数,即标量(scalar)类的数组:

const schema = await gqlSchemaFactory.create(
  [RecipesResolver, AuthorsResolver, PostsResolver],
  [DurationScalar, DateScalar],
);

最后,你还可以传入一个选项对象(与 GraphQLModule 配置的 buildSchemaOptions 属性所接受的 BuildSchemaOptions 相同):

const schema = await gqlSchemaFactory.create([RecipesResolver], {
  skipCheck: true,
  orphanedTypes: [],
});
  • skipCheck:跳过 schema 校验;布尔值,默认为 false
  • orphanedTypes:一组类的数组,即使它们未被显式引用(即不属于对象图的一部分)也会被生成。通常情况下,已声明但在图中任何位置都未被引用的类会被省略。

联邦

GraphQLSchemaFactory 构建的是普通 GraphQL schema:它对 Apollo Federation 一无所知。要获取代码优先的联邦子图的 SDL(例如把它传给 rover subgraph check 或 rover supergraph compose),请改用 @apollo/subgraph 包中的 printSubgraphSchema 而不是 printSchema 来打印,这样 @key、@shareable 或 @external 等指令才能保留下来:

import { printSubgraphSchema } from '@apollo/subgraph';

async function generateSchema() {
  const app = await NestFactory.create(GraphQLSchemaBuilderModule);
  await app.init();

  const gqlSchemaFactory = app.get(GraphQLSchemaFactory);
  const schema = await gqlSchemaFactory.create([UsersResolver], {
    orphanedTypes: [User],
  });
  console.log(printSubgraphSchema(schema));
}

对于 Federation 2,打印出的 SDL 还必须链接联邦规范,否则它会被当作 Federation 1 子图处理。你需要自行在前面加上 @link,并导入你的类型用到的每一个联邦指令:

const sdl = `extend schema @link(url: "https://specs.apollo.dev/federation/v2.14", import: ["@key", "@shareable", "@external"])

${printSubgraphSchema(schema)}`;
提示

仅通过 _entities 被引用的实体类型(例如用 @ResolveReference() 解析的 @extends 桩类型)无法从根类型到达,因此需要把它们放进 orphanedTypes 传入。否则,生成的 schema 中不会包含它们。