插件
插件使你能够通过对特定事件执行自定义操作来扩展 Apollo Server 的核心功能。目前,这些事件对应于 GraphQL 请求生命周期的各个阶段,以及 Apollo Server 本身的启动(更多信息请参阅这里)。例如,一个基本的日志插件可能会记录发送到 Apollo Server 的每个请求所关联的 GraphQL 查询字符串。
自定义插件
要创建插件,声明一个使用从 @nestjs/apollo 包导出的 @Plugin 装饰器注解的类。同时,为了获得更好的代码自动补全,需要实现从 @apollo/server 包导出的 ApolloServerPlugin 接口。
typescript
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 注册为提供者。
typescript
@Module({
providers: [LoggingPlugin],
})
export class CommonModule {}Nest 会自动实例化插件并将其应用到 Apollo Server。
使用外部插件
有一些开箱即用的插件可供使用。要使用现有插件,只需导入它并将其添加到 plugins 数组中:
typescript
GraphQLModule.forRoot({
// ...
plugins: [ApolloServerOperationRegistry({ /* options */})]
}),提示
ApolloServerOperationRegistry 插件从 @apollo/server-plugin-operation-registry 包导出。
Mercurius 插件
一些现有的 mercurius 特定 Fastify 插件必须在插件树中的 mercurius 插件之后加载(更多信息请参阅这里)。
警告
mercurius-upload 是一个例外,应在主文件中注册。
为此,MercuriusDriver 提供了一个可选的 plugins 配置选项。它表示一个对象数组,每个对象包含两个属性:plugin 和其 options。因此,注册缓存插件的方式如下:
typescript
GraphQLModule.forRoot({
driver: MercuriusDriver,
// ...
plugins: [
{
plugin: cache,
options: {
ttl: 10,
policy: {
Query: {
add: true
}
}
},
}
]
}),