1
|
import { Inject, Injectable, isDevMode } from '@angular/core';
|
2
|
|
3
|
@Injectable()
|
4
|
export class CacheService {
|
5
|
static KEY = 'CacheService';
|
6
|
|
7
|
constructor(@Inject('LRU') public _cache: Map<string, any>) {
|
8
|
|
9
|
}
|
10
|
|
11
|
/**
|
12
|
* check if there is a value in our store
|
13
|
*/
|
14
|
has(key: string | number): boolean {
|
15
|
let _key = this.normalizeKey(key);
|
16
|
return this._cache.has(_key);
|
17
|
}
|
18
|
|
19
|
/**
|
20
|
* store our state
|
21
|
*/
|
22
|
set(key: string | number, value: any): void {
|
23
|
let _key = this.normalizeKey(key);
|
24
|
this._cache.set(_key, value);
|
25
|
}
|
26
|
|
27
|
/**
|
28
|
* get our cached value
|
29
|
*/
|
30
|
get(key: string | number): any {
|
31
|
console.log("Cache get :"+key);
|
32
|
let _key = this.normalizeKey(key);
|
33
|
return this._cache.get(_key);
|
34
|
}
|
35
|
|
36
|
/**
|
37
|
* release memory refs
|
38
|
*/
|
39
|
clear(): void {
|
40
|
this._cache.clear();
|
41
|
}
|
42
|
|
43
|
/**
|
44
|
* convert to json for the client
|
45
|
*/
|
46
|
dehydrate(): any {
|
47
|
let json = {};
|
48
|
this._cache.forEach((value: any, key: string) => json[key] = value);
|
49
|
return json;
|
50
|
}
|
51
|
|
52
|
/**
|
53
|
* convert server json into out initial state
|
54
|
*/
|
55
|
rehydrate(json: any): void {
|
56
|
Object.keys(json).forEach((key: string) => {
|
57
|
let _key = this.normalizeKey(key);
|
58
|
let value = json[_key];
|
59
|
this._cache.set(_key, value);
|
60
|
});
|
61
|
}
|
62
|
|
63
|
/**
|
64
|
* allow JSON.stringify to work
|
65
|
*/
|
66
|
toJSON(): any {
|
67
|
return this.dehydrate();
|
68
|
}
|
69
|
|
70
|
/**
|
71
|
* convert numbers into strings
|
72
|
*/
|
73
|
normalizeKey(key: string | number): string {
|
74
|
if (isDevMode() && this._isInvalidValue(key)) {
|
75
|
throw new Error('Please provide a valid key to save in the CacheService');
|
76
|
}
|
77
|
|
78
|
return key + '';
|
79
|
}
|
80
|
|
81
|
_isInvalidValue(key): boolean {
|
82
|
return key === null ||
|
83
|
key === undefined ||
|
84
|
key === 0 ||
|
85
|
key === '' ||
|
86
|
typeof key === 'boolean' ||
|
87
|
Number.isNaN(<number>key);
|
88
|
}
|
89
|
}
|