UNPKG

@anglr/rest

Version:

Angular module representing rest services

92 lines 3.53 kB
import { Inject, Injectable } from '@angular/core'; import { isBlank } from '@jscrpt/common'; import { extend } from '@jscrpt/common/extend'; import { REST_DATE_API } from '../../misc/tokens'; import * as i0 from "@angular/core"; /** * Allows advanced caching of http responses */ export class AdvancedCacheService { //######################### constructor ######################### constructor(restDateApi) { this.restDateApi = restDateApi; //######################### protected fields ######################### /** * Instance of cache and its data */ this.cache = {}; } //######################### public methods ######################### /** * Clears cache either for specified key, or whole cache * @param key - Name of cache to be cleared, if not provided all cached items will be cleared */ clearCache(key) { if (isBlank(key)) { this.cache = {}; return; } delete this.cache[key]; } /** * Adds response to advanced cache * @param key - Key under which will be cached item stored * @param request - Request for which will be response added * @param response - Response to be cached * @param config - Configuration for cached response */ add(key, request, response, config) { this.cache[key] ??= {}; this.cache[key][request.urlWithParams] = { response, ...config }; return response; } /** * Gets http response from cache, or null if it does not exists * @param key - Key which represents cached item * @param request - Request for which will be response returned */ get(key, request) { const cachedItem = this.cache[key]; if (!cachedItem) { return null; } const cachedData = cachedItem[request.urlWithParams]; if (!cachedData) { return null; } if (cachedData.validUntil && !this.restDateApi.isBeforeNow(cachedData.validUntil)) { delete cachedItem[request.urlWithParams]; return null; } return cachedData.response; } /** * Updates existing cache items, if not exists it does nothing * @param key - Key which represents cached items * @param config - Config to be applied to existing cache items */ updateCache(key, config) { const cachedItem = this.cache[key]; if (!cachedItem) { return; } Object.keys(cachedItem).forEach(url => { const cachedData = cachedItem[url]; extend(cachedData, config); }); } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.0", ngImport: i0, type: AdvancedCacheService, deps: [{ token: REST_DATE_API }], target: i0.ɵɵFactoryTarget.Injectable }); } static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.1.0", ngImport: i0, type: AdvancedCacheService, providedIn: 'root' }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.0", ngImport: i0, type: AdvancedCacheService, decorators: [{ type: Injectable, args: [{ providedIn: 'root' }] }], ctorParameters: () => [{ type: undefined, decorators: [{ type: Inject, args: [REST_DATE_API] }] }] }); //# sourceMappingURL=advancedCache.service.js.map