Feeling like your NestJS API is lagging under heavy traffic?
Caching could be a secret weapon!
Why Use Caching?
Let's imagine running an e-commerce site where users frequently request products lists. Each request hits the database, slowing down performance as traffic grows. Caching helps by storing the product list temporarily, so subsequent requests are served faster without hitting the database again.
In this article, I'm going to show you how to implement data caching into NestJS app using @nestjs/cache-manager cache-manager
- Install the package
npm install @nestjs/cache-manager
2.In your module, import the cache module
import { Module } from '@nestjs/common';
import { CacheModule } from '@nestjs/cache-manager';
@Module({
imports: [CacheModule.register()],
})
export class ProductsModule {}
3.Inject the cache manager into your service and use it like this:
import { Inject, Injectable } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
@Injectable()
export class ProductsService {
private readonly productsCacheKey: string = 'your_key_here';
constructor(
@Inject(CACHE_MANAGER)
private readonly cacheManager: Cache,
) {}
public async set(
data: IProduct[],
ttl: number = 100000,
): Promise<void> {
await this.cacheManager.set(
productsCacheKey,
JSON.stringify(data),
ttl,
);
}
public async get(): Promise<string> {
return await this.cacheManager.get(productsCacheKey);
}
public async delete(): Promise<boolean> {
await this.cacheManager.del(productsCacheKey);
return true;
}
//Other methods
}
By adding caching to your NestJS app with @nestjs/cache-manager, you can improve performance and make your application handle high traffic more efficiently. Give it a try and see the difference it makes!
Top comments (0)