Skip to content

Instantly share code, notes, and snippets.

@felinto-dev
Created August 21, 2022 10:20
Show Gist options
  • Save felinto-dev/a72a44dbe8613e6b9d91697593ac086e to your computer and use it in GitHub Desktop.
Save felinto-dev/a72a44dbe8613e6b9d91697593ac086e to your computer and use it in GitHub Desktop.
Axios Cache Wrapper for NestJS
import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import {
setupCache,
buildMemoryStorage,
defaultKeyGenerator,
} from 'axios-cache-interceptor';
@Injectable()
export class ApiService {
constructor(private readonly httpService: HttpService) {}
private readonly axiosCacheWrapper = setupCache(this.httpService.axiosRef, {
storage: buildMemoryStorage(),
generateKey: defaultKeyGenerator,
});
async getAxiosRequest() {
const response = await this.axiosCacheWrapper.get(
'https://example.com/wp/v2/keywords',
{
params: {},
cache: {
ttl: 1000 * 60 * 60, // 1 hour
interpretHeader: false,
methods: ['get'],
cachePredicate: {
statusCheck: (status) => status >= 200 && status < 400,
},
},
},
);
return response.data;
}
}
@felinto-dev
Copy link
Author

If you want to declare the wrapper in module class:

consts.ts

const AXIOS_CACHE_WRAPPER_TOKEN = 'AXIOS_CACHE_WRAPPER_TOKEN';

app.module.ts

  providers: [
    {
      provide: AXIOS_CACHE_WRAPPER_TOKEN,
      useFactory: (httpService: HttpService) => {
        return setupCache(httpService.axiosRef, {
          storage: buildMemoryStorage(),
          generateKey: defaultKeyGenerator,
        });
      },
      inject: [HttpService],
    },
  ],

app.service.ts

import { AxiosCacheInstance } from 'axios-cache-interceptor';

    @Inject(AXIOS_CACHE_WRAPPER_TOKEN)
    private readonly axiosCacheWrapper: AxiosCacheInstance,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment