/** Angular Imports */ import { Injectable } from '@angular/core' ; import { HttpResponse } from '@angular/common/http' ; /** Other Imports */ import { each } from 'lodash' ; /** Custom Services */ import { Logger } from '../logger/logger.service' ; /** Initialize Logger */ const log = new Logger ( 'HttpCacheService' ) ; /** Http Cache Entry Model */ export interface HttpCacheEntry { lastUpdated : Date ; data : HttpResponse < any > ; } /**
 * Provides a cache facility for HTTP requests with configurable persistence policy.
 */ @ Injectable ( ) export class HttpCacheService { /** Key to cache Http Requests in storage. */ private cachePersistenceStorageKey = 'mifosXHttpCache' ; private cachedData : { [ key ] : HttpCacheEntry ; } = { } ; private storage : Storage | null = null ; constructor ( ) { this . loadCacheData ( ) ; } param { ! string } url param { ResponseOptions } data param { Date = } lastUpdated setCacheData ( url , data , lastUpdated ? ) { this . cachedData [ url ] = { lastUpdated : lastUpdated || new Date ( ) , data : data } ; log . debug ( `Cache set for key: "${ url }"` ) ; this . saveCacheData ( ) ; } param { ! string } url return { ? ResponseOptions } getCacheData ( url ) { const cacheEntry = this . cachedData [ url ] ; if ( cacheEntry ) { log . debug ( `Cache hit for key: "${ url }"` ) ; return cacheEntry . data ; } return null ; } param { ! string } url return { ? HttpCacheEntry } getHttpCacheEntry ( url ) { return this . cachedData [ url ] || null ; } param { ! string } url clearCache ( url ) { delete this . cachedData [ url ] ; log . debug ( `Cache cleared for key: "${ url }"` ) ; this . saveCacheData ( ) ; } param { date = } expirationDate cleanCache ( expirationDate ? ) { if ( expirationDate ) { each ( this . cachedData , ( value , key ) => { if ( expirationDate >= value . lastUpdated ) { delete this . cachedData [ key ] ; } } ) ; } else { this . cachedData = { } ; } this . saveCacheData ( ) ; } param { 'local' | 'session' = } persistence setPersistence ( persistence ? ) { this . cleanCache ( ) ; this . storage = persistence === 'local' || persistence === 'session' ? window [ persistence + 'Storage' ] : null ; this . loadCacheData ( ) ; } private saveCacheData ( ) { if ( this . storage ) { this . storage [ this . cachePersistenceStorageKey ] = JSON . stringify ( this . cachedData ) ; } } private loadCacheData ( ) { const data = this . storage ? this . storage [ this . cachePersistenceStorageKey ] : null ; this . cachedData = data ? JSON . parse ( data ) : { } ; } }