Total Complexity | 4 |
Total Lines | 32 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 0 |
1 | import {IObserverAdapter, IOnChangeCallback} from '../Observer/Observer'; |
||
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 | } |