Within our application we use the Axios HttpService to do some request to a third-party api. Because the amount of data returned bij de api is so huge, we would like to cache the responses. In the docs is wasn't able to find some examples of how to do this. I'm currently doing this as follows:
@Module({
imports: [
HttpModule,
CacheModule.register({
ttl: 15,
store: redisStore,
host: 'localhost',
port: 6379,
})
]
})
export class AppModule {}
I register the CacheModule globally. Then import it in the module where i need it.
In the service where i use the third-party api, i create an interceptor where i go and cache the reponses. Very crude and just for testing.
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));
}
First of all this doesn't run, because the CACHE_MANAGER can't be imported into the CacheModule, for some reason. Second this is a more a Node.js way of creating such interceptors and not the NestJS way. But is this a way to move forward or is there a more effecient way and if yes, what way is that?
The CacheModule is not the right tool here, as it means to cache ingoing requests (the requests your service receives, so it doesn't proceed them again and send back a cached result).
What you're trying to do is caching the outgoing requests (the one your service makes to 3rd-party services). For mysterious reasons, I couldn't find it documented in NestJS documentation either, but here's how you can go:
As you're using Axios, you can implement caching using the axios-cache-adapter npm package.
npm install --save axios-cache-adapter
Then you need to create an adapter (preferably in the constructor of your service, see notes below):
const cache = setupCache({
maxAge: 3600 * 1000, // 60 minutes
});
and provide this adapter as part of the AxiosRequestConfig alongside your request:
const config = {
adapter: this.cache.adapter,
};
this.httpService.get( url, config );
You should be good with some caching now!
IMPORTANT NOTES:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With