我想用nestjs将昂贵的GQL查询缓存在服务器端。
我跟踪了https://docs.nestjs.com/graphql/plugins#using-external-plugins和https://www.apollographql.com/docs/apollo-server/performance/caching/#caching-with-responsecacheplugin-advanced
我还看到了https://github.com/nestjs/graphql/issues/443#issuecomment-599445224,它建议它应该像预期的那样工作。
我在使用阿波罗联盟
我遇到的问题是,如果我在子图中添加responseCachePlugin,它就能正常工作(或多或少)。
但是,当我尝试在网关(即联合服务中)使用responseCachePlugin时,它就被忽略了:所有请求都会命中下游的子图。
package.json
"dependencies": {
...
"@nestjs/common": "^7.6.18",
"@nestjs/core": "^7.6.18",
"@nestjs/graphql": "^7.11.0",
"@nestjs/platform-express": "^7.6.18",
"apollo-server-express": "^2.25.0",
"apollo-server-plugin-response-cache": "^0.9.0",
...
"graphql": "^15.5.0",
"graphql-subscriptions": "^1.2.1",
"graphql-type-json": "^0.3.2",
...
}注意:使用0.9.0与2.25.0兼容(还不可能使用最新的3.2.0)
然后,在网关的“主”模块中,我有:
GraphQLGatewayModule.forRootAsync({
imports: [
LoggerModule,
BuildServiceModule,
ConfigModule.register(GwEnvVar, GW_DEFAULT_CONFIG),
],
inject: [ConfigService, GATEWAY_BUILD_SERVICE],
useFactory: (configService: ConfigService<GwEnvVar>) => ({
cors: true,
server: {
introspection:
configService.env.NODE_ENV === NodeEnv.PRODUCTION ? false : true,
playground: true,
cacheControl: {
defaultMaxAge: 5,
},
plugins: [responseCachePlugin()],
},
gateway: getSupergraphSchema('schema.gql', configService.env),
}),
}),
],
})
export class GraalModule {}应用程序启动正确,但是,正如我已经说过的,每个请求都会击中下游的子图。
还请注意,如果我将完全相同的配置直接放在子图中,那么解析器就不再被击中(然而,这意味着缓存是在子图中完成的,这不是我想要的)。
如果没有直接提供解决方案,是否有人有指针来解释缓存应该如何与阿波罗联邦(除了极简主义的doc https://www.apollographql.com/docs/apollo-server/performance/caching/#caching-with-responsecacheplugin-advanced和https://www.apollographql.com/docs/federation/performance/caching/之外)工作?
发布于 2022-06-11 00:28:43
我遇到了一个类似的问题(没有联邦),并发现需要添加以下内容:
在不使用阿波罗服务器(
apollo-server-plugin-response-cache之外,还需要安装apollo-cache-control。如果类型也是类型,则需要将@cacheControl添加到类型的字段中,并且必须与父字段匹配。否则,缓存控件maxAge将使用defaultMaxAge。例如: type Dog @cacheControl(maxAge: 100) {
dob: String,
name: String,
breed: Breed
}
type Breed @cacheControl(maxAge: 100) {
name: String!
size: Int
}https://stackoverflow.com/questions/69450479
复制相似问题