|
|
@ -7,11 +7,13 @@ export type TableOptions = {
|
|
|
|
|
|
|
|
|
|
|
|
export class Database {
|
|
|
|
export class Database {
|
|
|
|
connection!: Promise<IDBDatabase>;
|
|
|
|
connection!: Promise<IDBDatabase>;
|
|
|
|
|
|
|
|
tables!: TableOptions[];
|
|
|
|
|
|
|
|
|
|
|
|
constructor(public readonly database: string, public readonly tables: (string | TableOptions)[], public version?: number) {
|
|
|
|
constructor(public readonly database: string, tables: (string | TableOptions)[], public version?: number) {
|
|
|
|
this.connection = new Promise((resolve, reject) => {
|
|
|
|
this.connection = new Promise((resolve, reject) => {
|
|
|
|
const req = indexedDB.open(this.database, this.version);
|
|
|
|
const req = indexedDB.open(this.database, this.version);
|
|
|
|
const tableNames = new ASet(tables.map(t => (typeof t == 'object' ? t.name : t).toString()));
|
|
|
|
this.tables = tables.map(t => typeof t == 'object' ? t : {name: t});
|
|
|
|
|
|
|
|
const tableNames = new ASet(this.tables.map(t => t.name));
|
|
|
|
|
|
|
|
|
|
|
|
req.onerror = () => reject(req.error);
|
|
|
|
req.onerror = () => reject(req.error);
|
|
|
|
|
|
|
|
|
|
|
@ -29,16 +31,14 @@ export class Database {
|
|
|
|
req.onupgradeneeded = () => {
|
|
|
|
req.onupgradeneeded = () => {
|
|
|
|
const db = req.result;
|
|
|
|
const db = req.result;
|
|
|
|
const existingTables = new ASet(Array.from(db.objectStoreNames));
|
|
|
|
const existingTables = new ASet(Array.from(db.objectStoreNames));
|
|
|
|
console.log('delete', existingTables.difference(tableNames));
|
|
|
|
|
|
|
|
existingTables.difference(tableNames).forEach(name => db.deleteObjectStore(name));
|
|
|
|
existingTables.difference(tableNames).forEach(name => db.deleteObjectStore(name));
|
|
|
|
console.log('create', tableNames.difference(existingTables));
|
|
|
|
|
|
|
|
tableNames.difference(existingTables).forEach(name => db.createObjectStore(name));
|
|
|
|
tableNames.difference(existingTables).forEach(name => db.createObjectStore(name));
|
|
|
|
};
|
|
|
|
};
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
includes(name: string): boolean {
|
|
|
|
includes(name: any): boolean {
|
|
|
|
return this.tables.some(t => (typeof t === 'string' ? name === t : name === t.name));
|
|
|
|
return !!this.tables.find(t => t.name == name.toString());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
table<K extends IDBValidKey = any, T = any>(name: any): Table<K, T> {
|
|
|
|
table<K extends IDBValidKey = any, T = any>(name: any): Table<K, T> {
|
|
|
|