Nest 最新的版本为V9,较之前的V7/8有不小改动,GraphQL 部分官方文档之前的V8也是本人翻译的,有很多不完善的地方,这次打算重新精细翻译一遍,会持续更新这块内容,并最后贡献给中文文档仓库,为中文社区贡献一份力量。有兴趣的小伙伴记得要关注收藏。
警告 ⚠️
该章节仅适用于@nestjs/apollo驱动。
插件使你能够通过在某些事件的响应中执行自定义操作,来扩展 Apollo 服务器的核心功能。现在,这些事件可以对应到 GraphQL 请求生命周期的各个阶段,以及 Apollo 服务器本身的启动阶段(在此处阅读更多)。例如,一个基础的日志插件可能会记录与发送到Apollo服务器的每个请求相关联的GraphQL查询字符串
自定义插件
要创建一个插件,需要声明一个用@Plugin装饰器注释的类,该装饰器是从@nestjs/graphql包里导出的。此外,为了代码能够更好地自动完成,可以从apollo-server-plugin-base 包中实现 ApolloServerPlugin接口。
import { Plugin } from '@nestjs/apollo';
import {
ApolloServerPlugin,
GraphQLRequestListener,
} from 'apollo-server-plugin-base';
@Plugin()
export class LoggingPlugin implements ApolloServerPlugin {
async requestDidStart(): Promise<GraphQLRequestListener> {
console.log('Request started');
return {
async willSendResponse() {
console.log('Will send response');
},
};
}
}
有了这些,我们就可以把LoggingPlugin注册为一个提供者了。
@Module({
providers: [LoggingPlugin],
})
export class CommonModule {}
Nest将自动实例化这个插件并应用到Apollo服务器。
使用外部插件
有许多开箱即用的插件。要使用这些插件,只需将它们导入并添加到plugins数组即可:
GraphQLModule.forRoot({
// ...
plugins: [ApolloServerOperationRegistry({ /* options */})]
}),
提示
ApolloServerOperationRegistry插件是从apollo-server-plugin-operation-registry包里导出的。