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

DataStorage.attach   A

Complexity

Conditions 1

Size

Total Lines 7
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 7
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
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
}