插件(Plugin)可以让你扩展 Apollo Server 的核心功能,在特定事件发生时执行自定义操作。目前,这些事件主要对应于 GraphQL 请求生命周期的各个阶段,以及 Apollo Server 启动时(详细内容可参见这里)。例如,一个基础的日志插件可以在每次请求发送到 Apollo Server 时,记录对应的 GraphQL 查询字符串。
要创建插件,只需声明一个带有 @Plugin 装饰器(由 @nestjs/apollo 包导出)的类。同时,为了获得更好的代码自动补全体验,建议实现 @apollo/server 包中的 ApolloServerPlugin 接口(Interface)。
import { ApolloServerPlugin, GraphQLRequestListener } from '@apollo/server'
import { Plugin } from '@nestjs/apollo'
@Plugin()
export class LoggingPlugin implements ApolloServerPlugin {
async requestDidStart(): Promise<GraphQLRequestListener<any>> {
console.log('Request started')
return {
async willSendResponse() {
console.log('Will send response')
},
}
}
}有了上述代码后,我们可以将 LoggingPlugin 注册为 provider(提供者):
@Module({
providers: [LoggingPlugin],
})
export class CommonModule {}Nest 会自动实例化该插件,并将其应用到 Apollo Server 上。
有许多开箱即用的插件可供选择。要使用现有插件,只需导入并添加到 plugins 数组中即可:
GraphQLModule.forRoot({
// ...
plugins: [ApolloServerOperationRegistry({ /* options */})]
}),ApolloServerOperationRegistry 插件由
@apollo/server-plugin-operation-registry 包导出。
部分现有的 mercurius 专用 Fastify 插件,必须在 mercurius 插件之后加载(详细内容可参见这里)。
mercurius-upload 是个例外,必须在主文件中注册。
为此,MercuriusDriver 提供了一个可选的 plugins 配置项。它是一个对象数组,每个对象包含两个属性:plugin 和对应的 options。例如,注册 cache 插件 的方式如下:
GraphQLModule.forRoot({
driver: MercuriusDriver,
// ...
plugins: [
{
plugin: cache,
options: {
ttl: 10,
policy: {
Query: {
add: true
}
}
},
}
]
}),