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

DataStorage.loadData   A

Complexity

Conditions 2

Size

Total Lines 9
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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