/
service.ts
39 lines (33 loc) · 988 Bytes
/
service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
export class StorageService {
private memoryStorage: Object = {};
private namespace: string;
public constructor(namespace = 'app-store') {
this.namespace = namespace;
this.restore();
}
public setItem(key: string, value: unknown): void {
this.memoryStorage[key] = value;
this.store();
}
public getItem<T>(key: string): any {
return this.memoryStorage[key] as T;
}
public removeItem(key: string): void {
delete this.memoryStorage[key];
this.store();
}
private restore(): void {
try {
const sessionStorage = window.sessionStorage.getItem(this.namespace);
if (sessionStorage === null) {
throw new Error('Session store is empty.');
}
this.memoryStorage = <Object>JSON.parse(sessionStorage);
} catch (error) {
this.memoryStorage = <Object>require('./mock.json');
}
}
private store(): void {
window.sessionStorage.setItem(this.namespace, JSON.stringify(this.memoryStorage));
}
}