1.0.1 • Published 5 months ago
@dessly/nestjs-cacheable v1.0.1
nestjs-cacheable
Service-level caching for NestJS.
@dessly/nestjs-cacheable
extends the standard CacheModule
so you can cache service method calls—not only controller responses—using two simple decorators:
Decorator | Purpose |
---|---|
@Cacheable | Stores the method’s return value under a generated key & TTL. |
@CacheEvict | Removes one or many keys after the method finishes successfully. |
Installation
npm i @dessly/nestjs-cacheable # or
yarn add @dessly/nestjs-cacheable
Quick Start
// app.module.ts
import { Module, CacheModule } from '@nestjs/common';
import { CacheableModule } from '@knaus94/nestjs-cacheable';
@Module({
imports: [
CacheModule.register({ isGlobal: true }), // any cache-manager store
CacheableModule.register(), // default JSON serializer
],
})
export class AppModule {}
// user.service.ts
@Injectable()
export class UserService {
/** Result is cached for 5 seconds */
@Cacheable({
key: (id: number) => `username-${id}`,
namespace: 'user',
ttl: 5000, // milliseconds
})
async getUserName(id: number) {
return this.db.query(/* … */);
}
/** Cache entry is removed after deletion */
@CacheEvict({
key: (id: number) => `username-${id}`,
namespace: 'user',
})
async deleteUser(id: number) {
await this.db.delete(/* … */);
}
}
Item | Description |
---|---|
Cacheable(options) | Caches the method result. Options: key , namespace , ttl . |
CacheEvict(options) | Deletes keys after the method succeeds. |
CacheableModule.register(cfg) | Enables service-level caching.cfg.defaultTTL (ms) sets a fallback TTL. |