1 | import { typeIt } from '../../shares/utils';
|
2 | import * as MOCK from './mock.json';
|
3 |
|
4 | interface INameToValueMap {
|
5 | [key: string]: any;
|
6 | }
|
7 |
|
8 | const TYPED_MOCK = typeIt<INameToValueMap>(MOCK);
|
9 |
|
10 | export class StorageService {
|
11 | private memoryStorage: INameToValueMap = {};
|
12 | private namespace: string;
|
13 |
|
14 | public constructor(namespace = 'app-store') {
|
15 | this.namespace = namespace;
|
16 | this.restore();
|
17 | }
|
18 |
|
19 | public setItem(key: string, value: unknown): void {
|
20 | this.memoryStorage[key] = value;
|
21 | this.store();
|
22 | }
|
23 |
|
24 | public getItem<T>(key: string): any {
|
25 | return <T>this.memoryStorage[key];
|
26 | }
|
27 |
|
28 | public removeItem(key: string): void {
|
29 | delete this.memoryStorage[key];
|
30 | this.store();
|
31 | }
|
32 |
|
33 | private restore(): void {
|
34 | try {
|
35 | const sessionStorage = window.sessionStorage.getItem(this.namespace);
|
36 | if (sessionStorage === null) {
|
37 | throw new Error('Session store is empty.');
|
38 | }
|
39 | this.memoryStorage = <Object>JSON.parse(sessionStorage);
|
40 | } catch (error) {
|
41 | this.memoryStorage = <Object>TYPED_MOCK;
|
42 | }
|
43 | }
|
44 |
|
45 | private store(): void {
|
46 | window.sessionStorage.setItem(this.namespace, JSON.stringify(this.memoryStorage));
|
47 | }
|
48 | }
|