import { CacheItem } from './CacheItem' ; import * as crypto from 'crypto' ; export class Cache { private _cache : { [ key ] : CacheItem ; } = { } ; public set < T > ( key , data , expiration ? ) { let cacheItem = undefined ; key = this . getHashKey ( key ) ; if ( ! expiration ) { cacheItem = new CacheItem ( data ) ; } else if ( typeof expiration === 'number' ) { const now = 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 ) { key = this . getHashKey ( key ) ; const cacheItem = this . _cache [ key ] ; if ( ! cacheItem ) { return undefined ; } if ( ! cacheItem . expiredOn ) { return cacheItem . data ; } const now = new Date ( ) ; if ( now > cacheItem . expiredOn ) { this . remove ( key ) ; return undefined ; } else { return cacheItem . data ; } } public remove ( key ) { key = this . getHashKey ( key ) ; delete this . _cache [ key ] ; } public clear ( ) { this . _cache = { } ; } private getHashKey ( key ) { return crypto . createHash ( 'md5' ) . update ( key ) . digest ( 'hex' ) ; } }