Project

General

Profile

1
import { Injectable, isDevMode } from '@angular/core';
2

    
3
@Injectable()
4
export class CacheService {
5
  static KEY = 'CacheService';
6
  _cache = new Map();
7

    
8
  /**
9
   * check if there is a value in our store
10
   */
11
  has(key: string | number): boolean {
12
    let _key = this.normalizeKey(key);
13
    return this._cache.has(_key);
14
  }
15

    
16
  /**
17
   * store our state
18
   */
19
  set(key: string | number, value: any): void {
20
    let _key = this.normalizeKey(key);
21
    this._cache.set(_key, value);
22
  }
23

    
24
  /**
25
   * get our cached value
26
   */
27
  get(key: string | number): any {
28
    let _key = this.normalizeKey(key);
29
    return this._cache.get(_key);
30
  }
31

    
32
  /**
33
   * release memory refs
34
   */
35
  clear(): void {
36
    this._cache.clear();
37
  }
38

    
39
  /**
40
   * convert to json for the client
41
   */
42
  dehydrate(): any {
43
    let json = {};
44
    this._cache.forEach((value: any, key: string) => json[key] = value);
45
    return json;
46
  }
47

    
48
  /**
49
   * convert server json into out initial state
50
   */
51
  rehydrate(json: any): void {
52
    Object.keys(json).forEach((key: string) => {
53
      let _key = this.normalizeKey(key);
54
      let value = json[_key];
55
      this._cache.set(_key, value);
56
    });
57
  }
58

    
59
  /**
60
   * allow JSON.stringify to work
61
   */
62
  toJSON(): any {
63
    return this.dehydrate();
64
  }
65

    
66
  /**
67
   * convert numbers into strings
68
   */
69
  normalizeKey(key: string | number): string {
70
    if (isDevMode() && this._isInvalidValue(key)) {
71
      throw new Error('Please provide a valid key to save in the CacheService');
72
    }
73

    
74
    return key + '';
75
  }
76

    
77
  _isInvalidValue(key): boolean {
78
    return key === null ||
79
      key === undefined ||
80
      key === 0 ||
81
      key === '' ||
82
      typeof key === 'boolean' ||
83
      Number.isNaN(<number>key);
84
  }
85
}
(4-4/4)