-
Notifications
You must be signed in to change notification settings - Fork 1k
/
storage.ts
72 lines (58 loc) · 1.61 KB
/
storage.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
import { WebPlugin } from './index';
import {
StoragePlugin
} from '../core-plugin-definitions';
export class StoragePluginWeb extends WebPlugin implements StoragePlugin {
KEY_PREFIX = '_cap_';
constructor() {
super({
name: 'Storage',
platforms: ['web']
});
}
get(options: { key: string }): Promise<{value: string}> {
return new Promise((resolve, _reject) => {
resolve({
value: window.localStorage.getItem(this.makeKey(options.key))
});
});
}
set(options: { key: string, value: string }): Promise<void> {
return new Promise((resolve, _reject) => {
window.localStorage.setItem(this.makeKey(options.key), options.value);
resolve();
});
}
remove(options: { key: string }): Promise<void> {
return new Promise((resolve, _reject) => {
window.localStorage.removeItem(this.makeKey(options.key));
resolve();
});
}
keys(): Promise<{ keys: string[] }> {
return new Promise((resolve, _reject) => {
resolve({
keys: Object.keys(localStorage).filter(k => this.isKey(k)).map(k => this.getKey(k))
});
});
}
clear(): Promise<void> {
return new Promise((resolve, _reject) => {
Object.keys(localStorage)
.filter(k => this.isKey(k))
.forEach(k => window.localStorage.removeItem(k));
resolve();
});
}
makeKey(key: string) {
return this.KEY_PREFIX + key;
}
isKey(key: string) {
return key.indexOf(this.KEY_PREFIX) === 0;
}
getKey(key: string) {
return key.substr(this.KEY_PREFIX.length);
}
}
const Storage = new StoragePluginWeb();
export { Storage };