-
Notifications
You must be signed in to change notification settings - Fork 2
/
localstorage.js
384 lines (336 loc) · 12.6 KB
/
localstorage.js
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
class BasicEventHandler {
constructor () {
const eventPooler = {};
const getNamespace = (str="")=> {
const sl = str.split(".");
var major = sl.shift();
return {
"major": major,
"minor": sl.join(".") || "*"
}
}
var id = 0;
const makeId = ()=> {
id++;
return id;
}
this.on = (eventName, fn)=> {
if (typeof fn !== "function") throw new error("Second parameter must be a function");
const nameSpace = getNamespace(eventName);
eventPooler[nameSpace.major] ||= {};
eventPooler[nameSpace.major][nameSpace.minor] ||= {};
eventPooler[nameSpace.major][nameSpace.minor][makeId()] = {
fn:fn
};
}
this.one = (eventName, fn)=> {
if (typeof fn !== "function") throw new error("Second parameter must be a function")
const nameSpace = getNamespace(eventName);
eventPooler[nameSpace.major] ||= {};
eventPooler[nameSpace.major][nameSpace.minor] ||= {};
eventPooler[nameSpace.major][nameSpace.minor][makeId()] = {
fn:fn,
one:true
};
}
this.off = (eventName)=> {
if (!eventName.includes(".")) {
if (!eventPooler[eventName]) return;
delete eventPooler[eventName];
} else {
let nameSpace = getNamespace(eventName);
try{
delete eventPooler[nameSpace.major][nameSpace.minor];
} catch(e) {
}
}
}
this.emmit = (eventName, ...args)=> {
const nameSpace = getNamespace(eventName);
if (!eventPooler[nameSpace.major]) return;
if (!eventName.includes(".")) {
for (let minor in eventPooler[nameSpace.major]) {
for (let i in eventPooler[nameSpace.major][minor]) {
eventPooler[nameSpace.major][minor][i].fn.apply(this, args);
if (eventPooler[nameSpace.major][minor][i].one) {
delete eventPooler[nameSpace.major][minor][i];
if (Object.keys(eventPooler[nameSpace.major][minor]).length == 0 ) delete eventPooler[nameSpace.major][minor];
}
}
}
} else {
if (!eventPooler[nameSpace.major][nameSpace.minor]) return;
for (let i in eventPooler[nameSpace.major][nameSpace.minor]) {
eventPooler[nameSpace.major][nameSpace.minor][i].fn.apply(this, args);
if (eventPooler[nameSpace.major][nameSpace.minor][i].one) {
delete eventPooler[nameSpace.major][nameSpace.minor][i];
if (Object.keys(eventPooler[nameSpace.major][nameSpace.minor]).length == 0 ) delete eventPooler[nameSpace.major][nameSpace.minor];
}
}
}
}
this.hasEvent = (eventName) => {
try {
const nameSpace = getNamespace(eventName);
if (!eventPooler[nameSpace.major]) return false;
if (!eventName.includes(".")) {
if (Object.keys(eventPooler[nameSpace.major]).length > 0 ) return true;
} else {
if (Object.keys(eventPooler[nameSpace.major][nameSpace.minor]).length > 0) return true;
}
return false;
} catch (e) {
return false;
}
}
this.trigger = this.emmit;
}
}
/**
* A simple indexedDB handler to store [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) like key value pair... except, it is better.
* The benefits are:
* - Can store large amount of data.
* - Asynchronous and non-blocking.
* - Loaded on demand unlike LocalStorage.
* - Can store JavaScript object data.
* @class
* @param {String} [dbName=commonDB] - The DB name
* @param {String} [tableName=keyValuePairs] - Table name
* @memberof common
* @example <caption>Basic usage</caption>
* var myStorage = new DB();
*
* //store a value to "someKey"
* await myStorage.set("someKey", {"someObject" : "with the value"}):
*
* //get the value of "someKey"
* await myStorage.get("someKey");
* // will returns:
* {
* "someObject": "with the value"
* }
*/
const BLS = function(dbName="commonDB", tableName="keyValuePairs") {
const evt = new BasicEventHandler();
this.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
this.dbName = dbName || "commonDB";
this.tableName = tableName || "keyValuePairs";
// this.readyPromise = new Promise((resolve) => {
// this.resolver = resolve;
// });
const initTransaction = async () => {
const result = {}
result.tx = this.db.transaction(this.tableName, "readwrite");
result.store = result.tx.objectStore(this.tableName)
//this.tx = result.tx;
//this.store = result.store;
return result;
}
var initPromise;
const init = async () => {
if (initPromise) return initPromise;
initPromise = new Promise((resolve, reject) => {
const makeTableVersion = (ver)=> {
var dBOpenRequest;
if (!ver) {
dBOpenRequest = indexedDB.open(this.dbName);
} else {
dBOpenRequest = indexedDB.open(this.dbName, ver);
}
this.isInitialized = false;
dBOpenRequest.onupgradeneeded = (event) =>{
this.db = event.target.result;
this.store = this.db.createObjectStore(this.tableName, {keyPath: "id"});
//this.index = this.store.createIndex("NameIndex", ["name.last", "name.first"]);
this.db.onclose = () => {
evt.trigger("closed")
};
};
dBOpenRequest.onerror = (event) => {
console.error("Error connecting to DB", event);
reject(new Error("Cannot connect to database"))
}
dBOpenRequest.onsuccess = (event) => {
// Start a new transaction
const db = dBOpenRequest.result;
this.db = db;
//this.db.objectStoreNames.contains( this.tableName ) || this.db.createObjectStore( this.tableName );
//this.tx = this.db.transaction(this.tableName, "readwrite");
//this.store = this.tx.objectStore(this.tableName);
//this.index = this.store.index("NameIndex");
if (!db.objectStoreNames.contains( this.tableName )) {
db.onclose = () => {
evt.trigger("closed")
};
db.close();
setTimeout(() => {
makeTableVersion(db.version+1);
}, 200);
return;
}
this.isInitialized = true;
resolve(this);
}
}
makeTableVersion();
});
return initPromise;
}
this.untilReady = async () => {
if (this.isInitialized) return this;
return init();
}
/**
* Set a value to the local DB
* @async
* @param {String} key - key of the key-value pair
* @param {*} value - Value of the key-value pair. Value can be anything. Unlike LocalStorage, if you can also store object in the DB.
* @returns {Promise<Event>} - Transaction event
*/
this.set = async (key, value) => {
if (typeof key !== "string") throw new Error("Invalid key. Key must be a string!")
await this.untilReady();
evt.trigger("beforeSet", key, value);
var isChanged = false;
var prevValue
if (evt.hasEvent("change")) {
prevValue = await this.get(key);
if (JSON.stringify(prevValue) !== JSON.stringify(value)) isChanged = true;
}
return new Promise(async (resolve, reject) => {
const transaction = await initTransaction();
var request = transaction.store.put({id: key, value: value});
request.onsuccess = (e)=> {
evt.trigger("set", key, value);
if (isChanged) {
evt.trigger("change", key, value, prevValue);
}
resolve(e)
}
request.onerror = (e)=> {
reject(e)
}
})
}
this.setItem = this.set;
/**
* Get a value from local DB.
* @async
* @param {String} key - key of the key-value pair
* @returns {Promise<*>} - The value
*/
this.get = async (key) => {
if (typeof key !== "string") throw new Error("Invalid key. Key must be a string!")
await this.untilReady();
return new Promise(async (resolve, reject) => {
const transaction = await initTransaction();
var request = transaction.store.get(key);
request.onsuccess = (e)=> {
if (!request.result) return resolve();
resolve(request.result.value)
}
request.onerror = (e)=> {
reject(e)
}
})
}
this.getItem = this.get;
this.getAll = async () => {
await this.untilReady();
return new Promise(async (resolve, reject) => {
const transaction = await initTransaction();
var request = transaction.store.getAll();
request.onsuccess = (e)=> {
if (!request.result) return resolve();
let result = {}
for (let i=0; i<request.result.length; i++) {
result[request.result[i].id] = request.result[i].value;
}
resolve(result)
}
request.onerror = (e)=> {
reject(e)
}
})
}
/**
* Delete a record from local DB.
* @async
* @param {String} key - key of the key-value pair
* @returns {Promise<Event>} - Transaction event
*/
this.delete = async (key) => {
if (typeof key !== "string") throw new Error("Invalid key. Key must be a string!")
await this.untilReady();
evt.trigger("beforeDelete", key);
return new Promise(async (resolve, reject) => {
const transaction = await initTransaction();
var request = transaction.store.delete(key);
request.onsuccess = (e)=> {
evt.trigger("delete", key);
resolve(e)
}
request.onerror = (e)=> {
reject(e)
}
})
}
this.removeItem = this.delete;
/**
* Clear a database.
* @returns {Promise<Event>} - Transaction event
*/
this.clear = async () => {
await this.untilReady();
evt.trigger("beforeClear");
return new Promise(async (resolve, reject) => {
const transaction = await initTransaction();
var request = transaction.store.clear();
request.onsuccess = (e)=> {
evt.trigger("clear");
resolve(e)
}
request.onerror = (e)=> {
reject(e)
}
})
}
/**
* Completely remove the database.
* @returns {Promise<Event>} - Transaction event
*/
this.drop = async () => {
await this.untilReady();
evt.trigger("beforeDrop");
return new Promise(async (resolve, reject) => {
const request = indexedDB.deleteDatabase(this.dbName);
request.onsuccess = (e)=> {
evt.trigger("drop");
resolve(e)
}
request.onblocked = (e)=> {
resolve(e)
}
request.onerror = (e)=> {
reject(e)
}
})
}
/**
* Close connection to the database.
*/
this.close = async () => {
await this.untilReady();
this.db.close();
}
this.on = (eventName, fn)=> {
evt.on(eventName, fn);
}
this.one = (eventName, fn)=> {
evt.one(eventName, fn);
}
this.off = (eventName) => {
evt.off(eventName);
}
}
module.exports = BLS;