ttl-cache.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * @description
  3. * An in-memory cache with a configurable TTL (time to live) which means cache items
  4. * expire after they have been in the cache longer than that time.
  5. *
  6. * The `ttl` config option is in milliseconds. Defaults to 30 seconds TTL and a cache size of 1000.
  7. *
  8. * @deprecated Use the CacheService instead
  9. */
  10. export class TtlCache<K, V> {
  11. private cache = new Map<K, { value: V; expires: number }>();
  12. private readonly ttl: number = 30 * 1000;
  13. private readonly cacheSize: number = 1000;
  14. constructor(config?: { ttl?: number; cacheSize?: number }) {
  15. if (config?.ttl) {
  16. this.ttl = config.ttl;
  17. }
  18. if (config?.cacheSize) {
  19. this.cacheSize = config.cacheSize;
  20. }
  21. }
  22. get(key: K): V | undefined {
  23. const hit = this.cache.get(key);
  24. const now = new Date().getTime();
  25. if (hit) {
  26. if (now < hit.expires) {
  27. return hit.value;
  28. } else {
  29. this.cache.delete(key);
  30. }
  31. }
  32. }
  33. set(key: K, value: V) {
  34. if (this.cache.has(key)) {
  35. // delete key to put the item to the end of
  36. // the cache, marking it as new again
  37. this.cache.delete(key);
  38. } else if (this.cache.size === this.cacheSize) {
  39. // evict oldest
  40. const oldest = this.first();
  41. if (oldest) {
  42. this.cache.delete(oldest);
  43. }
  44. }
  45. this.cache.set(key, {
  46. value,
  47. expires: new Date().getTime() + this.ttl,
  48. });
  49. }
  50. delete(key: K) {
  51. this.cache.delete(key);
  52. }
  53. private first() {
  54. return this.cache.keys().next().value;
  55. }
  56. }