libs/caching/src/lib/http-get-cache/local-http-cache.ts
Properties |
|
Methods |
constructor(config: CacheConfig)
|
||||||
Parameters :
|
Public get | |||||||||
get(req: HttpRequest
|
|||||||||
Parameters :
Returns :
HttpResponse<any>
|
Public put | ||||||||||||
put(req: HttpRequest
|
||||||||||||
Parameters :
Returns :
void
|
Public Abstract get | |||||||||
get(req: HttpRequest
|
|||||||||
Inherited from
HttpCache
|
|||||||||
Defined in
HttpCache:11
|
|||||||||
Returns a cached response, if any, or null, if not present.
Parameters :
Returns :
HttpResponse | null
|
Public Abstract put | ||||||||||||
put(req: HttpRequest
|
||||||||||||
Inherited from
HttpCache
|
||||||||||||
Defined in
HttpCache:16
|
||||||||||||
Adds or updates the response in the cache.
Parameters :
Returns :
void
|
Private cache |
Type : Cache
|
Default value : {}
|
Private cachingDuration |
Type : number
|
Default value : 30000
|
Default caching duration |
import { HttpRequest, HttpResponse } from '@angular/common/http';
import { Inject, Injectable, Optional } from '@angular/core';
import { CacheConfig, CacheConfigService } from '../config';
import { HttpCache } from '../model';
interface CachedItem {
expirationAtMs: number;
response: HttpResponse<any>;
}
interface Cache {
[id: string]: CachedItem;
}
@Injectable()
export class LocalHttpCache extends HttpCache {
private cache: Cache = {};
/**
* Default caching duration
*/
private cachingDuration = 30000;
constructor(
@Optional() @Inject(CacheConfigService) config: CacheConfig
) {
super();
if (config && config.cachingDurationInMilliseconds) { this.cachingDuration = config.cachingDurationInMilliseconds; }
}
public get(req: HttpRequest<any>, expirationAtMs?: number): HttpResponse<any> {
const key = req.urlWithParams;
if (this.cache[key]) {
const currentTime = new Date().getTime();
if (isNaN(this.cache[key].expirationAtMs)) {
this.cache[key].expirationAtMs = expirationAtMs;
return this.cache[key].response;
} else {
if (this.cache[key].expirationAtMs >= currentTime) {
if (this.cache[key].expirationAtMs > expirationAtMs) { this.cache[key].expirationAtMs = expirationAtMs; }
return this.cache[key].response;
} else {
delete this.cache[key];
}
}
}
return null;
}
public put(req: HttpRequest<any>, resp: HttpResponse<any>, expirationAtMs?: number) {
this.cache[req.urlWithParams] = {
expirationAtMs: expirationAtMs || new Date().getTime() + this.cachingDuration,
response: resp
};
}
}