All files / src/classes CoreTimeCache.ts

96.55% Statements 28/29
87.5% Branches 14/16
100% Functions 13/13
96.55% Lines 28/29

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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135                                        1x       1x     1x 1x 1x             1x       1x 4x 4x 4x 4x 1x   4x                       3x                       1x               4x               2x               4x                 3x 1x   3x                 1x 1x     1x 1x 1x             1x 1x        
import CoreLogChannel from './CoreLogChannel';
import CMap from './CoreMap';
import type { IHaveLogger } from '../lib';
 
export type CachedData<T> = {
  last: number;
  ttl: number;
  data: T;
};
/**
 * A cache that stores values with a time‑to‑live (TTL) and automatically removes
 * expired entries after a configurable interval.
 *
 * The cache stores data objects wrapped in a `CachedData<T>` structure that
 * tracks the insertion time (`last`) and the remaining TTL. When an entry
 * expires, a background loop removes it and optionally logs the event.
 *
 * @template T The type of the cached data.
 */
export default class CoreTimeCache<T> extends CoreLogChannel {
  private cache = new CMap<string, CachedData<T>>();
 
  private readonly loopTime: number;
 
  private interval: NodeJS.Timeout | null = null;
 
  constructor(name: string, log: IHaveLogger | null = null, loopTime = 10000) {
    super(name, log);
    this.cache = new CMap<string, CachedData<T>>();
    this.loopTime = loopTime;
  }
 
  /**
   * Flash the cache
   */
  flash() {
    this.cache.clear();
  }
 
  private startBackground() {
    this.interval = setInterval(() => {
      const now = new Date().getTime();
      this.cache.deleteSelected((v, key) => {
        const res = v.last + v.ttl < now;
        if (res) {
          this.log(`clearing cache ${key}`);
        }
        return res;
      });
    }, this.loopTime);
  }
 
  /**
   *
   * @param key cache key
   * @param data data to cache
   * @param ttl time in ms
   */
  set(key: string, data: T, ttl = 120000) {
    this.setRaw(key, {
      last: new Date().getTime(),
      ttl,
      data,
    });
  }
 
  /**
   * Delete cached data
   * @param key
   */
  delete(key: string) {
    this.cache.delete(key);
  }
 
  /**
   * Get cached data
   * @param key
   */
  get(key: string): T | null {
    return this.getRaw(key)?.data ?? null;
  }
 
  /**
   * Has cached data
   * @param key
   */
  has(key: string) {
    return this.cache.has(key);
  }
 
  /**
   * Get raw cached data object
   * @param key
   */
  getRaw(key: string): CachedData<T> | null {
    return this.cache.get(key) || null;
  }
 
  /**
   * Get raw cached data object
   * @param key
   * @param data
   */
  setRaw(key: string, data: CachedData<T>): void {
    if (!this.interval) {
      this.startBackground();
    }
    this.cache.set(key, data);
  }
 
  /**
   * Extend the ttl of a cached data
   * @param key cache key
   * @param ttl add time in ms
   */
  extend(key: string, ttl = 120000): boolean {
    const el = this.cache.get(key);
    Iif (!el) {
      return false;
    }
    el.ttl += ttl;
    this.cache.set(key, el);
    return true;
  }
 
  /**
   * Stop the background cache cleaner
   */
  stop() {
    Eif (this.interval) {
      clearInterval(this.interval);
    }
  }
}