Skip to content

生成 SDL(Generating SDL)

警告

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

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

typescript
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));
}

提示

GraphQLSchemaBuilderModuleGraphQLSchemaFactory@nestjs/graphql 包导入。printSchema 函数从 graphql 包导入。

用法

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

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

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

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

最后,你可以传递一个选项对象:

typescript
const schema = await gqlSchemaFactory.create([RecipesResolver], {
  skipCheck: true,
  orphanedTypes: [],
});
  • skipCheck:忽略 schema 验证;布尔值,默认为 false
  • orphanedTypes:未被显式引用(不属于对象图的一部分)但需要生成的类列表。通常,如果一个类已声明但在图中未被引用,它将被省略。该属性值是一个类引用的数组。

基于 NestJS 官方文档翻译