2020-11-26 00:29:10 -05:00
|
|
|
import * as Comlink from "comlink";
|
2021-01-26 19:57:23 -05:00
|
|
|
import { importDB, exportDB } from "dexie-export-import";
|
2021-01-27 00:24:13 -05:00
|
|
|
import { encode } from "@msgpack/msgpack";
|
2020-11-26 00:29:10 -05:00
|
|
|
|
|
|
|
import { getDatabase } from "../database";
|
|
|
|
|
|
|
|
// Worker to load large amounts of database data on a separate thread
|
2021-01-27 00:24:13 -05:00
|
|
|
let service = {
|
2021-01-21 22:59:05 -05:00
|
|
|
/**
|
|
|
|
* Load either a whole table or individual item from the DB
|
|
|
|
* @param {string} table Table to load from
|
|
|
|
* @param {string|undefined} key Optional database key to load, if undefined whole table will be loaded
|
|
|
|
*/
|
|
|
|
async loadData(table, key) {
|
2020-11-26 01:08:09 -05:00
|
|
|
try {
|
|
|
|
let db = getDatabase({});
|
2021-01-21 22:59:05 -05:00
|
|
|
if (key) {
|
|
|
|
// Load specific item
|
2021-01-27 00:24:13 -05:00
|
|
|
return await db.table(table).get(key);
|
2021-01-21 22:59:05 -05:00
|
|
|
} else {
|
|
|
|
// Load entire table
|
2021-01-27 00:24:13 -05:00
|
|
|
let items = [];
|
2021-01-21 22:59:05 -05:00
|
|
|
// Use a cursor instead of toArray to prevent IPC max size error
|
2021-01-27 00:24:13 -05:00
|
|
|
await db.table(table).each((item) => items.push(item));
|
|
|
|
|
|
|
|
// Pack data with msgpack so we can use transfer to avoid memory issues
|
|
|
|
const packed = encode(items);
|
|
|
|
return Comlink.transfer(packed, [packed.buffer]);
|
2021-01-21 22:59:05 -05:00
|
|
|
}
|
2020-11-26 01:08:09 -05:00
|
|
|
} catch {}
|
2020-11-26 00:29:10 -05:00
|
|
|
},
|
2021-01-26 19:57:23 -05:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Export current database
|
|
|
|
* @param {function} progressCallback
|
|
|
|
*/
|
|
|
|
async exportData(progressCallback) {
|
|
|
|
try {
|
|
|
|
let db = getDatabase({});
|
2021-01-27 00:24:13 -05:00
|
|
|
return await exportDB(db, {
|
2021-01-26 19:57:23 -05:00
|
|
|
progressCallback,
|
|
|
|
numRowsPerChunk: 1,
|
|
|
|
});
|
|
|
|
} catch {}
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Import into current database
|
|
|
|
* @param {Blob} data
|
|
|
|
* @param {function} progressCallback
|
|
|
|
*/
|
|
|
|
async importData(data, progressCallback) {
|
|
|
|
try {
|
|
|
|
await importDB(data, { progressCallback });
|
|
|
|
} catch {}
|
|
|
|
},
|
2020-11-26 00:29:10 -05:00
|
|
|
};
|
|
|
|
|
2021-01-27 00:24:13 -05:00
|
|
|
Comlink.expose(service);
|