This repository was archived by the owner on Nov 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathwebStorage.ts
75 lines (61 loc) · 1.81 KB
/
webStorage.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import {parseJSON} from './util';
import {driverType} from "./interfaces";
export default class WebStorage {
public readonly storage: Storage;
constructor(public readonly prefix = 'app_', driver: driverType = 'local') {
this.storage = this.resolveDriver(driver);
}
prefixKey(key: string): string {
return this.prefix + String(key)
}
set(key: string, value: any): void {
return this.storage.setItem(this.prefixKey(key), JSON.stringify(value));
}
get<T extends any>(key: string, defaultValue: string | any = null): T {
let storedValue: null | any = null;
const item = this.storage.getItem(this.prefixKey(key));
if (!!item) {
storedValue = parseJSON(item);
}
return storedValue === null ? defaultValue : storedValue;
}
remove(key: string): void {
return this.storage.removeItem(this.prefixKey(key));
}
clear(force = false): void {
if (force) {
this.storage.clear();
} else {
this.keys(true).map((key) => {
this.storage.removeItem(key);
});
}
}
keys(withPrefix = false): string[] {
const keys: any[] = [];
// Loop through all storage keys
Object.keys(this.storage).forEach((keyName) => {
/* istanbul ignore else */
if (keyName.substr(0, this.prefix.length) === this.prefix) {
keys.push(withPrefix ? keyName : keyName.substring(this.prefix.length));
}
});
return keys;
}
hasKey(key: string): boolean {
return this.keys().indexOf(key) !== -1;
}
length(): number {
return this.keys().length;
}
private resolveDriver(driver: driverType): Storage {
switch (driver) {
case 'local':
return window.localStorage;
case 'session':
return window.sessionStorage;
default:
throw new Error(`Unknown driver supplied: ${driver}`)
}
}
}