NestJS生产环境报持久化查询无界缓存错误,无法找到配置入口
解决NestJS生产环境Apollo持久化查询无界缓存告警
问题背景
开发环境无报错,生产环境出现Apollo安全告警:
Persisted queries are enabled and are using an unbounded cache. Your server is vulnerable to denial of service attacks via memory exhaustion. Set
cache: "bounded"orpersistedQueries: falsein your ApolloServer constructor, or see https://go.apollo.dev/s/cache-backends for other alternatives.
使用的核心依赖版本:
@nestjs/apollo: 10.0.19@nestjs/common: 9.0.5@nestjs/core: 9.0.5@nestjs/graphql: 10.0.20
解决方案
在NestJS的GraphQL模块配置中,通过apolloServerOptions字段直接传递ApolloServer的原生配置参数,具体实现如下:
1. 同步配置方式
在app.module.ts的GraphQLModule配置里添加apolloServerOptions:
import { Module } from '@nestjs/common'; import { GraphQLModule } from '@nestjs/graphql'; import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo'; @Module({ imports: [ GraphQLModule.forRoot<ApolloDriverConfig>({ driver: ApolloDriver, autoSchemaFile: true, // 保留你的现有配置 // 新增ApolloServer核心配置 apolloServerOptions: { // 方案一:启用有界缓存(推荐) cache: 'bounded', // 方案二:关闭持久化查询 // persistedQueries: false, }, }), ], }) export class AppModule {}
2. 异步配置方式
如果使用动态加载配置的forRootAsync模式:
GraphQLModule.forRootAsync<ApolloDriverConfig>({ driver: ApolloDriver, useFactory: () => ({ autoSchemaFile: true, // 保留你的现有配置 apolloServerOptions: { cache: 'bounded', // 或者选择关闭持久化查询:persistedQueries: false }, }), }),
说明
@nestjs/apollo本质是对ApolloServer的封装,所有ApolloServer原生支持的配置参数都可以通过apolloServerOptions传入,这是官方封装的通用配置入口,可覆盖ApolloServer的构造器参数。
内容的提问来源于stack exchange,提问作者Nditah
相关产品推荐
相关产品推荐

