-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBrowserStorage.js
More file actions
323 lines (283 loc) · 10.4 KB
/
BrowserStorage.js
File metadata and controls
323 lines (283 loc) · 10.4 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/**
* Use browser storage
* @updated 25.09.13
* @copyright 2025 Hold'inCorp.
* @author inLoad
* @license Apache-2.0 ./LICENSE
*
* @see https://developer.mozilla.org/docs/Web/API/Web_Storage_API
*/
class BrowserStorage {
/**
* Return all data in storage
*/
static get all(){
throw new Error(`You have to implement the method "${this.name}.all()" !`);
}
/**
* this.length is protected by Javascript
*/
static get size(){ return this.all.length }
/**
* Return the name of the nth key in a given Storage object
*/
static key(nth){ return this.all.key(nth) }
/**
* Return specific data in storage
* @param {string} name
* @param {function} reviver
* @return {json}
*/
static get(name, reviver=undefined){
let data = this.all.getItem(name);
return data ? JSON.parse(data, reviver) : null;
}
/**
* Add or update data in storage
* @param {string} name
* @param {rest} data
*/
static set(name,...data){
if(!!data.length){
this.all.setItem(name,JSON.stringify(...data));
}
}
/**
* Remove data in storage
* @param {string} name
*/
static kill(name){
this.all.removeItem(name);
}
/**
* Clear all data in storage
*/
static clear(){
this.all.clear();
}
}
/**
* Local storage
* @extends BrowserStorage
* @see https://developer.mozilla.org/docs/Web/API/Window/localStorage
*/
class LocalBS extends BrowserStorage { static get all(){ return localStorage } }
/**
* Session storage
* @extends BrowserStorage
* @see https://developer.mozilla.org/docs/Web/API/Window/sessionStorage
*/
class SessionBS extends BrowserStorage { static get all(){ return sessionStorage } }
/**
* @typedef {Object} IndexConfig
* @property {string} name - The name of the index
* @property {string} keyPath - The key path for the index
* @property {IDBIndexParameters} [options] - Optional index parameters (unique, multiEntry, etc.)
*/
/**
* @typedef {Object} StoreConfig
* @property {string} keyPath - Primary key for the store
* @property {boolean} [autoIncrement=true] - Automatically increment the key if missing
* @property {IndexConfig[]} [indexes] - Optional indexes for the store
*/
/**
* IndexedBS
* A wrapper for IndexedDB with:
* - Robust versioning
* - Structured error handling
* - CRUD API with singular/plural methods
* - Change listeners
* - API access via `db.api[storeName]` to avoid naming conflicts
* - Full JSDoc typedefs for autocomplete and maintainability
*/
class IndexedBS {
/**
* @param {string} dbName - Name of the database
* @param {Record<string, StoreConfig>} stores - Configuration of stores
* @param {number} version - Initial database version
*/
constructor(dbName, stores = {}, version = 1) {
this.dbName = dbName;
this.version = version;
this.stores = stores;
this.db = null;
/** @type {Record<string, any>} API object for stores to avoid conflicts */
this.api = {};
}
/**
* Opens the database, creates stores if needed, and updates the version if necessary.
* @returns {Promise<IndexedBS>} Resolves when database is ready.
*/
async open() {
const currentVersion = await this._getCurrentVersion();
const needsUpgrade = await this._checkStores(currentVersion);
// Handling to prevent VersionError
if(needsUpgrade){
this.version = currentVersion + 1;
} else {
this.version = currentVersion;
}
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.dbName, this.version);
request.onupgradeneeded = event => {
this.db = event.target.result;
for(const [name, config] of Object.entries(this.stores)){
if (!this.db.objectStoreNames.contains(name)) {
const store = this.db.createObjectStore(name, {
keyPath: config.keyPath || "id",
autoIncrement: config.autoIncrement ?? true
});
if (config.indexes) {
config.indexes.forEach(idx =>
store.createIndex(idx.name, idx.keyPath, idx.options || {})
);
}
}
}
};
request.onsuccess = event => {
this.db = event.target.result;
this._createStoreAccessors();
resolve(this);
};
request.onerror = e => reject(e.target.error);
});
}
/** @private Get current DB version, return default if DB does not exist */
async _getCurrentVersion() {
return new Promise(resolve => {
const req = indexedDB.open(this.dbName);
req.onsuccess = e => {
const db = e.target.result;
resolve(db.version);
db.close();
};
req.onerror = () => resolve(this.version);
});
}
/**
* @private
* Checks if all stores exist, returns true if upgrade is needed
*/
async _checkStores(currentVersion) {
return new Promise((resolve, reject) => {
const req = indexedDB.open(this.dbName, currentVersion);
let needsUpgrade = false;
req.onsuccess = e => {
const db = e.target.result;
for(const name of Object.keys(this.stores)){
if(!db.objectStoreNames.contains(name)){
needsUpgrade = true;
break;
}
}
db.close();
resolve(needsUpgrade);
};
req.onerror = e => reject(e.target.error);
});
}
/**
* @private
* Read transaction wrapper with executor
* @param {string} storeName
* @param {Function} executor(store, resolve, reject)
*/
_read(storeName, executor) {
return new Promise((resolve, reject) => {
const tx = this.db.transaction(storeName, "readonly");
const store = tx.objectStore(storeName);
executor(store, resolve, reject);
// tx.oncomplete can be used for logging or cleanup
// tx.oncomplete = () => {};
tx.onerror = e => reject(e.target.error);
});
}
/**
* @private
* Write transaction wrapper for single or multiple items
* Collects all errors in an array
*/
_write(storeName, action, values, notifyFn = null) {
const items = Array.isArray(values) ? values : [values];
const results = [];
const errors = [];
return new Promise((resolve, reject) => {
const tx = this.db.transaction(storeName, "readwrite");
const store = tx.objectStore(storeName);
items.forEach(item => {
const req = store[action](item);
req.onsuccess = e => results.push(e.target.result);
req.onerror = e => {
const err = e.target.error;
errors.push({
item,
error: err.name === "ConstraintError" ? "DuplicateKey" : err
});
};
});
tx.oncomplete = () => {
if (notifyFn) items.forEach(v => notifyFn(action, v));
errors.length ? reject(errors) : resolve(items.length > 1 ? results : results[0]);
};
tx.onerror = () => reject(errors.length ? errors : "Transaction failed");
});
}
/** @private Create API accessors for all stores */
_createStoreAccessors() {
for(const storeName of Object.keys(this.stores)){
this.api[storeName] = this._createStore(storeName);
}
}
/** @private Create a store accessor with full CRUD + listeners */
_createStore(storeName) {
const listeners = [];
const notify = (action, data) => listeners.forEach(fn => fn(action, data));
return {
// WRITE
add: item => this._write(storeName, "add", item, notify),
adds: items => this._write(storeName, "add", items, notify),
update: item => this._write(storeName, "put", item, notify),
updates: items => this._write(storeName, "put", items, notify),
delete: key => this._write(storeName, "delete", key, notify),
deletes: keys => this._write(storeName, "delete", keys, notify),
// READ
get: key => this._read(storeName, (store, resolve, reject) => {
const req = store.get(key);
req.onsuccess = e => resolve(e.target.result);
req.onerror = e => reject(e.target.error);
}),
getAll: () => this._read(storeName, (store, resolve, reject) => {
const req = store.getAll();
req.onsuccess = e => resolve(e.target.result);
req.onerror = e => reject(e.target.error);
}),
filter: predicate => this._read(storeName, (store, resolve, reject) => {
const results = [];
const req = store.openCursor();
req.onsuccess = e => {
const cursor = e.target.result;
if (cursor) {
if (predicate(cursor.value)) results.push(cursor.value);
cursor.continue();
} else resolve(results);
};
req.onerror = e => reject(e.target.error);
}),
query: (indexName = null, query = null) => this._read(storeName, (store, resolve, reject) => {
const results = [];
const source = indexName ? store.index(indexName) : store;
const req = source.openCursor(query);
req.onsuccess = e => {
const cursor = e.target.result;
if (cursor) {
results.push(cursor.value);
cursor.continue();
} else resolve(results);
};
req.onerror = e => reject(e.target.error);
}),
onChange: fn => listeners.push(fn)
};
}
}