All files / src/utils Cache.ts

70% Statements 21/30
50% Branches 6/12
66.67% Functions 4/6
70% Lines 21/30
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 601x 1x   1x   6x     8x 8x   8x   8x 8x 8x 8x         8x       24x 24x   24x 8x     16x       16x   16x       16x                           32x      
import { CacheItem } from './CacheItem';
import * as crypto from 'crypto';
 
export class Cache {
 
  private _cache: { [key: string]: CacheItem } = {};
 
  public set(key: string, data: any, expiration?: number | Date): void {
    let cacheItem: CacheItem = undefined;
    key = this.getHashKey(key);
 
    Iif (!expiration) {
      cacheItem = new CacheItem(data);
    } else Eif (typeof expiration === 'number') {
      let now: Date = new Date();
      now.setSeconds(now.getSeconds() + expiration);
      cacheItem = new CacheItem(data, now);
    } else if (expiration instanceof Date) {
      cacheItem = new CacheItem(data, expiration);
    }
 
    this._cache[key] = cacheItem;
  }
 
  public get<T>(key: string): T {
    key = this.getHashKey(key);
    let cacheItem: CacheItem = this._cache[key];
 
    if (!cacheItem) {
      return undefined;
    }
 
    Iif (!cacheItem.expiredOn) {
      return cacheItem.data;
    }
 
    let now: Date = new Date();
 
    Iif (now > cacheItem.expiredOn) {
      this.remove(key);
      return undefined;
    } else {
      return cacheItem.data;
    }
  }
 
  public remove(key: string): void {
    key = this.getHashKey(key);
    delete this._cache[key];
  }
 
  public clear(): void {
    this._cache = {};
  }
 
  private getHashKey(key: string): string {
    return crypto.createHash('md5').update(key).digest('hex');
  }
}