-
-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathStorage.ts
More file actions
93 lines (77 loc) · 2.26 KB
/
Storage.ts
File metadata and controls
93 lines (77 loc) · 2.26 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { open } from './functions';
import { type DB } from './types';
type StorageOptions = {
location?: string;
encryptionKey?: string;
};
/**
* Creates a new async-storage api compatible instance.
* The encryption key is only used when compiled against the SQLCipher version of op-sqlite.
*/
export class Storage {
private db: DB;
constructor(options: StorageOptions) {
this.db = open({ ...options, name: '__opsqlite_storage.sqlite' });
this.db.executeSync('PRAGMA mmap_size=268435456');
this.db.executeSync(
'CREATE TABLE IF NOT EXISTS storage (key TEXT PRIMARY KEY, value TEXT) WITHOUT ROWID'
);
}
async getItem(key: string): Promise<string | undefined> {
const result = await this.db.execute(
'SELECT value FROM storage WHERE key = ?',
[key]
);
let value = result.rows[0]?.value;
if (typeof value !== 'undefined' && typeof value !== 'string') {
throw new Error('Value must be a string or undefined');
}
return value;
}
getItemSync(key: string): string | undefined {
const result = this.db.executeSync(
'SELECT value FROM storage WHERE key = ?',
[key]
);
let value = result.rows[0]?.value;
if (typeof value !== 'undefined' && typeof value !== 'string') {
throw new Error('Value must be a string or undefined');
}
return value;
}
async setItem(key: string, value: string) {
await this.db.execute(
'INSERT OR REPLACE INTO storage (key, value) VALUES (?, ?)',
[key, value.toString()]
);
}
setItemSync(key: string, value: string) {
this.db.executeSync(
'INSERT OR REPLACE INTO storage (key, value) VALUES (?, ?)',
[key, value.toString()]
);
}
async removeItem(key: string) {
await this.db.execute('DELETE FROM storage WHERE key = ?', [key]);
}
removeItemSync(key: string) {
this.db.executeSync('DELETE FROM storage WHERE key = ?', [key]);
}
async clear() {
await this.db.execute('DELETE FROM storage');
}
clearSync() {
this.db.executeSync('DELETE FROM storage');
}
getAllKeys() {
return this.db
.executeSync('SELECT key FROM storage')
.rows.map((row: any) => row.key);
}
/**
* Deletes the underlying database file.
*/
delete() {
this.db.delete();
}
}