All files / src/services cache.service.ts

22.22% Statements 4/18
0% Branches 0/7
0% Functions 0/5
13.33% Lines 2/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 421x               1x                                                                  
import {bind, BindingScope} from '@loopback/core';
 
interface CacheEntry {
  value: any;
  expiredAt: number;
}
 
@bind({scope: BindingScope.SINGLETON})
export class CacheService {
  private store = new Map<string, CacheEntry>();
  private defaultTtlMs = 60_000;
 
  get<T>(key: string): T | null {
    const entry = this.store.get(key);
    if (!entry) return null;
    if (Date.now() > entry.expiredAt) {
      this.store.delete(key);
      return null;
    }
    return entry.value as T;
  }
 
  set(key: string, value: any, ttlMs = this.defaultTtlMs) {
    this.store.set(key, {
      value,
      expiredAt: Date.now() + ttlMs,
    });
  }
 
  delete(key: string) {
    this.store.delete(key);
  }
 
  invalidateByPmoId(pmoId: number) {
    for (const key of this.store.keys()) {
      if (key.startsWith(`attachment:pmo:${pmoId}`)) {
        this.store.delete(key);
      }
    }
  }
}