Graphql

模式生成器

学习如何在 NestJS 中手动生成 GraphQL SDL 模式,包括使用 GraphQLSchemaBuilderModule 和配置选项。

模式生成器

生成 SDL

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

要手动生成 GraphQL SDL 模式(即不运行应用程序、不连接数据库、不挂载解析器等),请使用 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));
}

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

使用方法

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

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

它还接受第二个可选参数,包含标量类数组:

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

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

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