警告 ⚠️
此章节仅适用于代码优先方式
要手动生成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,
PostsResolvers,
]);
它还有第二个可选的参数,接收一组标量类:
const schema = await gqlSchemaFactory.create(
[RecipesResolver, AuthorsResolver, PostsResolvers],
[DurationScalar, DateScalar],
);
最后,你还可以传递一个可选的对象:
const schema = await gqlSchemaFactory.create([RecipesResolver], {
skipCheck: true,
orphanedTypes: [],
});
skipCheck:忽略schema 验证;布尔值,默认是falseorphanedTypes:要生成的未明确引用(不是对象图的一部份)的类列表。通常,如果声明了一个类但未在图中以其他方式引用,则会将其省略。该属性值就是一组类引用。
译者注:
具体的使用方法官方文档没有说明,是在命令行直接使用 Node 执行此 JS 文件函数。