cache.service.ts
nest.js/03-advanced/code/cache/cache.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class CacheService {
// In-memory cache (for tutorial purposes)
// In production, use Redis or similar
private cache: Map<string, { value: any; expiresAt: number }> = new Map();
async get<T>(key: string): Promise<T | null> {
const item = this.cache.get(key);
if (!item) {
return null;
}
if (Date.now() > item.expiresAt) {
this.cache.delete(key);
return null;
}
return item.value as T;
}
async set(key: string, value: any, ttl: number = 300): Promise<void> {
const expiresAt = Date.now() + ttl * 1000;
this.cache.set(key, { value, expiresAt });
}
async del(key: string): Promise<void> {
this.cache.delete(key);
}
async clear(): Promise<void> {
this.cache.clear();
}
}
Articoli correlati
app.controller.ts
app.controller.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/app.controller.ts).
Leggi l'articolo →app.module.ts
app.module.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/app.module.ts).
Leggi l'articolo →app.service.ts
app.service.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/app.service.ts).
Leggi l'articolo →main.ts
main.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/main.ts).
Leggi l'articolo →todos.controller.ts
todos.controller.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/todos/todos.controller.ts).
Leggi l'articolo →todos.module.ts
todos.module.ts — typescript source code from the nest.js learning materials (nest.js/01-beginner/code/todos/todos.module.ts).
Leggi l'articolo →