-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLocalDatabase.all.js
539 lines (477 loc) · 22 KB
/
LocalDatabase.all.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
/**
* The schema for a column using LocalDatabase.
*/
class ColumnSchema {
/**
* @typedef ColumnSchemaOptions
* @property {Boolean} unique If true, the column will not allow duplicate values for a single key.
* @property {Boolean} multiEntry If true, the column will add an entry in the entry for each array element when the keyPath resolves to an array. If false, it will add one single entry containing the array.
* @property {String} locale A string containing a specific locale code, e.g. en-US, or pl
*/
/**
* The options you want to initialise this column with.
* @type {ColumnSchemaOptions}
*/
options = {
unique: false,
multiEntry: false,
locale: null
};
/**
* The name of the column.
* @type {String}
*/
name = "";
/**
* Generates a column blueprint for use in the TableSchema.
* @param {String} name The name of the column.
* @param {ColumnSchemaOptions} [options] The options you want to initialise this column with.
*/
constructor(name, options = this.options) {
this.name = name;
this.options = options;
}
}
/**
* The schema for a database using LocalDatabase.
*/
class DatabaseSchema {
/**
* The name of your database.
* @type {String}
*/
name = "";
/**
* The tables of your database.
* @type {Array.<TableSchema>}
*/
tables = [];
/**
* The names of all the tables in this database paired with the table schemas.
* @type {Object.<TableSchema>}
*/
tableMap = {};
/**
* The names of all the tables in this database.
* @type {Array.<String>}
*/
tableNames = [];
/**
* Generates a database blueprint for use in LocalDatabase.
* @param {String} name
* @param {Array.<TableSchema>} [tables] An array of the tables you want to have in this database.
*/
constructor(name, tables = []) {
this.name = name;
this.tables = tables;
tables.map(table => {
this.tableMap[table.name] = table;
this.tableNames.push(table.name);
});
}
}
/**
* The schema for a table using LocalDatabase.
*/
class TableSchema {
/**
* The name of the table.
* @type {String}
*/
name = ""
/**
* The primary column of the table.
* In other software this may be referred to as a keypath or a primary key.
* This must not have any duplicates!
* @type {ColumnSchema}
*/
keyColumn = null;
/**
* The columns that are not the keyColumn that reside in this table.
* @type {Array.<ColumnSchema>}
*/
otherColumns = [];
/**
* If true, the table has a key generator.
* @type {Boolean}
*/
autoIncrement = false;
/**
* Generates a table blueprint for use in DatabaseSchema.
* @param {String} name
* @param {ColumnSchema} keyColumn The primary column for this table. This column must not have any duplicates!
* @param {Array.<ColumnSchema>} [otherColumns] An array of all of the other columns you want to have in this table.
* @param {Boolean} [autoIncrement] If true, the table has a key generator.
*/
constructor(name, keyColumn, otherColumns = [], autoIncrement = false) {
if(!name) throw Error("Error in TableSchema. Attempting to generate a table without providing a table name.");
if(!keyColumn) throw Error("Error in TableSchema. Attempting to generate a table without providing a key column.");
if(otherColumns.includes(keyColumn) || new Set(otherColumns).size !== otherColumns.length) console.warn("Warning in TableSchema. You are trying to generate a table using duplicate columns. Make sure you have not included your chosen keyColumn in the \"otherColumns\" parameter.");
this.name = name
this.keyColumn = keyColumn;
this.otherColumns = otherColumns;
this.autoIncrement = autoIncrement;
}
}
/**
* A local database to handle local data storage such as the information about `items`.
*/
class LocalDatabase {
/**
* Instance of IndexedDB.
* @see https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase
* @type {IDBDatabase}
*/
static instance = undefined;
/**
* The version of your database. Upgrade this each time you want to add new features.
*
* The version of the database determines the database schema — the object stores in the database and their structure.
* @see https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/version
*/
static version = 1;
/**
* The schema used to initialise this database.
* @type {DatabaseSchema}
*/
static schema = null;
/**
* Initialise the LocalDatabase system.
* @param {DatabaseSchema} schema The database schema. Something like: {cats: [id, age, name]}
* @async Make sure to await this method's completion before using any of the LocalDatabase database methods (select, add).
*/
static init(schema) {
if (!window.indexedDB) {
throw Error("Your browser doesn't support a stable version of IndexedDB. As such, this app cannot run properly.");
}
LocalDatabase.schema = schema;
// Attempt to access the IndexedDB API
window.indexedDB.deleteDatabase(schema.name);
const opening = window.indexedDB.open(schema.name, LocalDatabase.version);
return new Promise((success, reject) => {
opening.onerror = event => {
console.error("Error: LocalDatabase opening error", event);
reject(new Error(`Error in opening IndexedDb. Make sure your browser supports IndexedDb and that you accept the request to initialise a local database. Also make sure you are running the right version!\n\nIndexedDb error:\n${event.target.error.name}: ${event.target.error.message}`));
}
opening.onblocked = event => {
console.error("Error: LocalDatabase blocked", event);
throw Error("Error in opening IndexedDb. There can only be one instance of this game running at a time. Please close that game before continuing.");
}
opening.onupgradeneeded = event => {
LocalDatabase.instance = event.target.result;
LocalDatabase.upgrade(schema);
}
opening.onsuccess = event => {
LocalDatabase.instance = event.target.result;
console.log("LocalDatabase initialised!");
success(event);
LocalDatabase.instance.onerror = event => {
LocalDatabase.error(event)
}
LocalDatabase.instance.onversionchange = event => {
LocalDatabase.instance.close();
console.warn("A new version of this page is ready. Please reload or close this tab!");
// @todo do something to make the user close this tab.
}
}
})
}
/**
* Upgrades the database using the provided schema.
* @param {*} schema
*/
static upgrade(schema) {
/**
* @important Make sure you update the `LocalDatabase.version`
*/
// Set the tables (object stores)
for(const table of schema.tables) {
// Add tables to the definition
const tableStore = LocalDatabase.instance.createObjectStore(table.name, { keyPath: table.keyColumn.name, autoIncrement: table.autoIncrement });
// Set the columns (indexes)
for(const column of table.otherColumns) {
tableStore.createIndex(column.name, column.name, column.options);
}
}
}
/**
* Inserts (or updates on collision) multiple items to a table.
* @param {String} table
* @param {Array.<Object>} objects
* @param {AddOptions} options
* @returns {Promise} Promise that resolves when all inserts have completed successfully.
* @async
*/
static multiAdd(table, objects, options = { upsert: true }) {
return Promise.all(objects.map(object => LocalDatabase.add(table, object, options)));
}
/**
* @typedef AddOptions
* @property {Boolean} upsert https://en.wikipedia.org/wiki/Merge_(SQL)#Synonymous
*/
/**
* Inserts (or updates on collision) an item to a table.
* @param {String} table
* @param {Object} object
* @param {AddOptions} options
* @returns {Promise}
* @async
*/
static add(table, object, options = { upsert: true }) {
if(!LocalDatabase.instance) throw Error("Error in LocalDatabase.add: The database has not yet been initialised! Please make sure you run `await LocalDatabase.init()` before using this.");
if(!table) throw Error("Error in LocalDatabase.add: No store defined.");
if(!LocalDatabase.schema.tableNames.includes(table)) throw Error(`Error in LocalDatabase.select: The specified table (${table}) was not found in the schema used to initialise the database.`);
return new Promise((success, reject) => {
const txn = LocalDatabase.instance.transaction(table, "readwrite");
const store = txn.objectStore(table);
if(options.upsert)
store.put(object);
else
store.add(object);
txn.oncomplete = event => {
success(event);
}
txn.onerror = event => {
console.error(`Error in LocalDatabase.add for store (${table}). Object, Options, Event:`, object, options, event);
reject(new Error(`Error in LocalDatabase.add for store (${table}). Check console.`));
}
})
}
/**
* Queries the store to select all entries matching the query.
*
* **Selects are structured as:**
*
* `{ columnName: desiredValue }`
*
* or
*
* `{ columnName: { $lt: desiredMax, $gt: desiredMin, $ne: notEqualTo } }`
*
* @note All column queries are 1 layer deep. Querying columns that contain objects is not currently possible.
*
* @note Range selectors are $lt (Less Than), $lte (Less Than or Equal To), $gt (Greater Than), $gte (Greater Than or Equal To), and $ne (Not Equal To)
*
* @param {String} table
* @param {*} query
*/
static select(table, query) {
if(!LocalDatabase.instance) throw Error("Error in LocalDatabase.select: The database has not yet been initialised! Please make sure you run `await LocalDatabase.init()` before using this.");
if(!table) throw Error("Error in LocalDatabase.select: No table defined.");
if(!LocalDatabase.schema.tableNames.includes(table)) throw Error(`Error in LocalDatabase.select: The specified table (${table}) was not found in the schema used to initialise the database.`);
return new Promise((success, reject) => {
// Destructure query into $lt, $lte, $gte, $gt, $ne
// The below arrays will be populated with a series of arrays like: [columnName, columnEntry]
const additiveQueries = [];
const subtractiveQueries = [];
for(const [columnName, columnEntry] of Object.entries(query)) {
// Basic query for exact matches
if(LocalDatabase._isPrimitive(columnEntry) || columnEntry === null) {
additiveQueries.push([columnName, columnEntry]);
continue;
}
// Get the highest greater than value
let greaterThan = columnEntry.$gt !== undefined ? columnEntry.$gt : columnEntry.$gte;
if(columnEntry.$gt !== undefined && columnEntry.$gte !== undefined) {
greaterThan = Math.max(columnEntry.$gt, columnEntry.$gte);
}
const isGte = greaterThan === columnEntry.$gte;
// Get the lowest less than value
let lessThan = columnEntry.$lt !== undefined ? columnEntry.$lt : columnEntry.$lte;
if(columnEntry.$lt !== undefined && columnEntry.$lte !== undefined) {
lessThan = Math.min(columnEntry.$lt, columnEntry.$lte);
}
const isLte = lessThan === columnEntry.$lte;
// Within a range
if(lessThan !== undefined && greaterThan !== undefined)
additiveQueries.push([columnName, IDBKeyRange.bound(greaterThan, lessThan, !isGte, !isLte)]);
// Less than, no greater than
if(lessThan !== undefined && greaterThan === undefined)
additiveQueries.push([columnName, IDBKeyRange.upperBound(columnEntry.$lt, !isLte)]);
// Greater than, no less than
if(lessThan === undefined && greaterThan !== undefined)
additiveQueries.push([columnName, IDBKeyRange.lowerBound(columnEntry.$gt, !isGte)]);
// Not equal to
if(columnEntry.$ne !== undefined)
subtractiveQueries.push([columnName, columnEntry.$ne]);
}
/**
* Gets an array of promises from a set of queries to be actioned on.
* @param {Array} queryArray
* @returns {Array}
*/
const getPromisesFromQueryArray = queryArray => {
const txn = LocalDatabase.instance.transaction(table, "readonly");
const store = txn.objectStore(table);
const allPromises = [];
for(const query of queryArray) {
allPromises.push(new Promise(complete => {
const index = LocalDatabase._getIndex(store, query[0], "Error in LocalDatabase.select"); // [0] is the columnName
const action = index.getAll(query[1]); // [1] is the value we want
action.onsuccess = event => complete(event.target.result)
action.onerror = event => {
console.error(`Error in LocalDatabase.select for store (${table}). Query, Event:`, query, event);
reject(new Error(`Error in LocalDatabase.select for store (${table}). Check console.`));
}
}))
}
return allPromises;
}
// Perform additive queries
const additivePromises = getPromisesFromQueryArray(additiveQueries);
// Perform subtractive queries
const subtractivePromises = getPromisesFromQueryArray(subtractiveQueries);
// Await all additive promises' completion
Promise.all(additivePromises).then(additiveResult => {
// If there is just 1 result, and there is no $ne queries return that.
if(subtractiveQueries.length === 0 && additiveResult.length <= 1) {
success(additiveResult[0]);
return;
}
/**
* Uses LocalDatabase._consolidate to consolidate the arrays nested within the array of arrays provided.
* @param {Array.<Array>} arrayOfArrays
* @returns {Array.<Array>} This result will be the consolidated and stringified version of the passed array.
*/
const intersectAndStringifyArrayOfArrays = arrayOfArrays => {
// NOTE: Because the results are objects, we have to turn them into primitives for comparison
let isFirst = true;
return arrayOfArrays.reduce((accumulation, current) => {
// Skip the first element (premature optimisation maybe)
if(isFirst) {
isFirst = false;
return accumulation;
}
// Convert all entries of the current array to JSON.
return LocalDatabase._intersect(accumulation, LocalDatabase._stringifyArrayElements(current));
}, LocalDatabase._stringifyArrayElements(arrayOfArrays[0])); // We need the initial value to be the first entry otherwise we will always get nothing because the intersection of nothing with something is nothing.
}
// Merge results
const stringifiedAdditiveResults = intersectAndStringifyArrayOfArrays(additiveResult);
// If we do not need to remove any results using subtractive queries, return.
if(subtractivePromises.length === 0) {
success(LocalDatabase._parseArrayElements(stringifiedAdditiveResults));
return;
}
// Filter out subtractive queries
Promise.all(subtractivePromises).then(subtractiveResult => {
const stringifiedSubtractiveResults = intersectAndStringifyArrayOfArrays(subtractiveResult);
const stringifiedMergedResults = LocalDatabase._difference(stringifiedAdditiveResults, stringifiedSubtractiveResults);
success(LocalDatabase._parseArrayElements(stringifiedMergedResults));
return;
});
})
})
}
static delete(table, query) {
if(!LocalDatabase.instance) throw Error("Error in LocalDatabase.delete: The database has not yet been initialised! Please make sure you run `await LocalDatabase.init()` before using this.");
if(!table) throw Error("Error in LocalDatabase.delete: No table defined.");
if(!LocalDatabase.schema.tableNames.includes(table)) throw Error(`Error in LocalDatabase.delete: The specified table (${table}) was not found in the schema used to initialise the database.`);
return new Promise(success => {
// Select all entries to be deleted
LocalDatabase.select(table, query).then(results => {
// Find out what the key column is for this table
const tableSchema = LocalDatabase.schema.tableMap[table];
const keyColumn = tableSchema.keyColumn.name;
// Get an array of keys from the results.
const keyArray = results.map(entry => entry[keyColumn]);
// Initiate delete
const deletePromises = [];
for(const key of keyArray) {
deletePromises.push(new Promise((delSuccess, delReject) => {
const txn = LocalDatabase.instance.transaction([tableSchema.name], "readwrite");
txn.objectStore(tableSchema.name).delete(key);
txn.oncomplete = event => {
delSuccess(event);
}
txn.onerror = event => {
console.error(`Error in LocalDatabase.delete for store (${table}). Query, Event:`, query, event);
reject(new Error(`Error in LocalDatabase.delete for store (${table}). Check console.`));
}
}))
}
Promise.all(deletePromises).then(resolution => success(resolution));
});
})
}
/**
* Gets an index from an object store.
* @param {IDBObjectStore} store
* @param {String} name
* @param {String} errorMessagePrepend
* @returns {IDBIndex}
*/
static _getIndex(store, name, errorMessagePrepend) {
try {
return store.index(name);
} catch (error) {
throw Error(`${errorMessagePrepend}\nErrored while trying to find column (${name}) in table (${store.name}). Make sure your specified column exists and is available!\n\nIndexedDb Error:\n${error.message}`);
}
}
/**
* Merges an array with a base array to create a new array from entries that only appear in both arrays.
* @param {Array} baseArray
* @param {Array} arrayToMerge
*/
static _intersect(baseArray, arrayToMerge) {
return arrayToMerge.filter(entry => baseArray.includes(entry));
}
/**
* Asymmetrically gets the difference of the two passed arrays.
* @example LocalDatabase._difference(['a', 'b', 'c', 'd'], ['a', 'b']) // Result: ["c", "d"]
* @example LocalDatabase._difference(['a', 'b'], ['a', 'b', 'c', 'd']) // Result: []
* @param {Array} baseArray
* @param {Array} arrayToMerge
*/
static _difference(baseArray, arrayToCompare) {
return baseArray.filter(entry => !arrayToCompare.includes(entry));
}
/**
* Returns true or false depending on whether or not the given variable is a primitive.
* @param {*} variable
* @return {Boolean}
*/
static _isPrimitive(variable) {
return["number", "string", "boolean", "bigint", "symbol"].includes(typeof variable);
}
/**
* Stringifies all of an array's elements using `JSON.stringify`.
* @example [{name:"bob"}] becomes ['{"name":"bob"}']
* @param {Array} array
* @returns {Array}
*/
static _stringifyArrayElements(array) {
return array.map(element => JSON.stringify(element))
}
/**
* De-stringifies all of an array's elements using `JSON.stringify.
* @example ['{"name":"bob"}'] becomes [{name:"bob"}]
* @param {Array} array
* @returns {Array}
*/
static _parseArrayElements(array) {
return array.map(element => JSON.parse(element));
}
/**
* Handle database errors. Probably should rework this to show more information.
* @param {*} event
*/
static error(event) {
throw Error(`Error with LocalDatabase. Error: ${event.target.errorCode}`);
}
/**
* The schema for a column using LocalDatabase.
* @type {ColumnSchema}
*/
static Column = ColumnSchema;
/**
* The schema for a table using LocalDatabase.
* @type {TableSchema}
*/
static Table = TableSchema;
/**
* The schema for a database using LocalDatabase.
* @type {DatabaseSchema}
*/
static Database = DatabaseSchema;
}