Created
August 21, 2022 10:20
-
-
Save felinto-dev/a72a44dbe8613e6b9d91697593ac086e to your computer and use it in GitHub Desktop.
Axios Cache Wrapper for NestJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
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
What does this code do?
Create a wrapper using the Axios Cache interceptor library to cache requests to an API using Axios in NestJS.
https://axios-cache-interceptor.js.org/#/
If you want to invalidate the cache when an external agent sends you a notification, you can use this method to do so:
https://axios-cache-interceptor.js.org/#/pages/invalidating-cache