-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDynamicIndexedDatabase.mjs
56 lines (55 loc) · 2.16 KB
/
DynamicIndexedDatabase.mjs
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
import IndexedDatabase from "./IndexedDatabase.mjs";
import "./PromiseWithResolvers.mjs";
class DynamicIndexedDatabase {
static #checkInstance(instance) { if (!(instance instanceof this)) throw new TypeError("Illegal invocation") }
#db;
static #rejectConstruct = true;
constructor(db) {
if (DynamicIndexedDatabase.#rejectConstruct) throw new TypeError("Illegal constructor");
DynamicIndexedDatabase.#rejectConstruct = true;
this.#db = db;
}
static #pool = new WeakMap;
static async open(name) {
if (arguments.length < 1) throw new TypeError("Failed to execute 'open': 1 argument required, but only 0 present.");
if (typeof name != "string") throw new TypeError("Failed to execute 'open': Argument 'name' is not a string.");
const db=await IndexedDatabase.open(name),pool = this.#pool, cache=pool.get(db);
if (cache) return cache;
DynamicIndexedDatabase.#rejectConstruct = false;
const instance = new DynamicIndexedDatabase(db);
pool.set(db, instance);
return instance;
}
#queue = [];
#processing = false;
initialStore(name, configure) {
DynamicIndexedDatabase.#checkInstance(this);
if (typeof name != "string") throw new TypeError("Failed to execute 'initialStore' on 'DynamicIndexedDatabase': Argument 'name' is not a string.");
if (typeof configure != "function") throw new TypeError("Failed to execute 'initialStore' on 'DynamicIndexedDatabase': Argument 'configure' is not a function.");
const adapter = Promise.withResolvers();
this.#queue.push({ adapter, name, configure });
this.#process();
return adapter.promise;
}
async #process() {
if (this.#processing) return;
this.#processing = true;
const database = this.#db,queue = this.#queue;
while (queue.length) {
const { name, configure, adapter: { resolve, reject } } = queue.shift();
try {
if (!database.objectStoreNames.contains(name)) await database.restart(Date.now(), configure);
resolve(database.getObjectStore(name));
} catch(e) {reject(e)}
}
this.#processing = false;
}
static {
Object.defineProperty(this.prototype, Symbol.toStringTag, {
value: this.name,
configurable: true
});
}
}
export default DynamicIndexedDatabase;
export { DynamicIndexedDatabase };