小编Ted*_*zen的帖子

在 NestJS 中缓存 axios httpService

在我们的应用程序中,我们使用 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 方式。但这是一种前进的方式还是有更有效的方式?如果有,那是什么方式?

caching axios nestjs

4
推荐指数
1
解决办法
3739
查看次数

标签 统计

axios ×1

caching ×1

nestjs ×1