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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you want to declare the wrapper in module class:
consts.ts
app.module.ts
app.service.ts