在 NestJS 中缓存 axios httpService

Ted*_*zen 4 caching axios nestjs

在我们的应用程序中,我们使用 Axios HttpService 向第三方 api 发出一些请求。由于 bij de api 返回的数据量非常大,因此我们希望缓存响应。在文档中无法找到如何执行此操作的一些示例。我目前正在这样做:

@Module({
  imports: [
    HttpModule,
    CacheModule.register({
      ttl: 15,
      store: redisStore,
      host: 'localhost',
      port: 6379,
    })
  ]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

我在全局注册 CacheModule。然后将其导入到我需要的模块中。

在我使用第三方 API 的服务中,我创建了一个拦截器并缓存响应。非常粗糙,仅供测试。

constructor(private readonly httpService: HttpService,
              private readonly cache: CacheStore) {
    httpService.axiosRef.interceptors.response.use((response) => {
      cache.set(response.request.url, response.data);
      return response;
    }, error => Promise.reject(error));
  }
Run Code Online (Sandbox Code Playgroud)

首先,这不会运行,因为由于某种原因,CACHE_MANAGER 无法导入到 CacheModule 中。其次,这是创建此类拦截器的 Node.js 方式,而不是 NestJS 方式。但这是一种前进的方式还是有更有效的方式?如果有,那是什么方式?

Bob*_*Bob 7

CacheModule在这里不是正确的工具,因为它意味着缓存传入请求(您的服务收到的请求,因此它不会再次处理它们并发回缓存结果)。

您想要做的是缓存传出请求(您的服务向第三方服务发出的请求)。由于神秘的原因,我也找不到 NestJS 文档中的记录,但您可以这样做:


当您使用 Axios 时,您可以使用axios-cache-adapter npm 包来实现缓存。

npm install --save axios-cache-adapter
Run Code Online (Sandbox Code Playgroud)

然后您需要创建一个适配器(最好在服务的构造函数中,请参阅下面的注释):

const cache = setupCache({
  maxAge: 3600 * 1000, // 60 minutes
});
Run Code Online (Sandbox Code Playgroud)

并提供此适配器作为 AxiosRequestConfig 的一部分以及您的请求:

const config = {
  adapter: this.cache.adapter,
};
this.httpService.get( url, config );
Run Code Online (Sandbox Code Playgroud)

您现在应该擅长一些缓存了!

重要笔记:

  • 应该仅在 GET 请求上使用缓存,并且可能会起作用
  • 仅使用setupCache函数一次(例如在服务的构造函数中);如果为每个请求创建一个缓存对象,则该缓存每次都会为空,这违背了它的目的