Passed
Push — master ( ea6aae...edf917 )
by Endre
53s queued 11s
created

src/DataStorage.ts   A

Complexity

Total Complexity 4
Complexity/F 1.33

Size

Lines of Code 41
Function Count 3

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
eloc 32
mnd 1
bc 1
fnc 3
dl 0
loc 41
bpm 0.3333
cpm 1.3333
noi 0
c 0
b 0
f 0
ccs 19
cts 19
cp 1
rs 10

3 Functions

Rating   Name   Duplication   Size   Complexity  
A DataStorage.attach 0 7 1
A DataStorage.loadData 0 9 2
A DataStorage.updateStorage 0 3 1
1
import {IObserverAdapter, IOnChangeCallback} from '@enbock/state-value-observer/Observer';
2 1
import StorageAdapter from './StorageAdapter';
3
4
export interface IAdapterDictionary {
5
  [index: string]: StorageAdapter<any>
6
}
7
8 1
export default class DataStorage {
9
  protected domain: string;
10
  protected storage: Storage;
11
  protected adapters: IAdapterDictionary;
12
13
  constructor(domain: string, storage: Storage) {
14 3
    this.domain = domain;
15 3
    this.storage = storage;
16 3
    this.adapters = {};
17
  }
18
19 1
  attach<T>(key: string, adapter: IObserverAdapter<T>): StorageAdapter<T> {
20 1
    const callback: IOnChangeCallback<T> = (newValue: T) => this.updateStorage(key, newValue);
21 1
    const storageAdapter: StorageAdapter<T> = new StorageAdapter<T>(adapter, callback);
22 1
    this.adapters[key] = storageAdapter;
23
24 1
    return storageAdapter;
25
  }
26
27 1
  loadData<T>(key: string, initialValue: T): T {
28 2
    const initJSON: string | null = this.storage.getItem(this.domain + '::' + key);
29 2
    let data: T = initialValue;
30 2
    if (initJSON != null) {
31 1
      data = JSON.parse(initJSON) as T;
32
    }
33
34 2
    return data;
35
  }
36
37 1
  protected updateStorage<T>(key: string, newValue: T) {
38 1
    this.storage.setItem(this.domain + '::' + key, JSON.stringify(newValue));
39
  }
40
}
41