Passed
Push — develop ( 215336...a05353 )
by Endre
03:50
created

src/Storage/DataStorage.ts   A

Complexity

Total Complexity 4
Complexity/F 1.33

Size

Lines of Code 40
Function Count 3

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 100%

Importance

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

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