import { createRxDatabase, addRxPlugin } from "rxdb"; import { RxDBUpdatePlugin } from "rxdb/plugins/update"; import { RxDBAttachmentsPlugin } from "rxdb/plugins/attachments"; import { RxDBQueryBuilderPlugin } from "rxdb/plugins/query-builder"; import { getRxStorageDexie } from "rxdb/plugins/storage-dexie"; import { wrappedKeyEncryptionCryptoJsStorage } from "rxdb/plugins/encryption-crypto-js"; import { settingsSchema, attachmentSchema } from "./schemas"; addRxPlugin(RxDBQueryBuilderPlugin); addRxPlugin(RxDBUpdatePlugin); addRxPlugin(RxDBAttachmentsPlugin); let _getDatabase; // cached let isDevPluginAdded = false; const DB_NAME = "taskbar-db"; const isDev = process.env.NODE_ENV === "development"; async function addDevPlugin() { // https://rxdb.info/dev-mode.html if (isDev && !isDevPluginAdded) { await import("rxdb/plugins/dev-mode").then(({ RxDBDevModePlugin }) => { isDevPluginAdded = true; return addRxPlugin(RxDBDevModePlugin); }); } } async function createCollections(db) { await db.addCollections({ settings: { schema: settingsSchema, }, }); await db.addCollections({ attachments: { schema: attachmentSchema, }, }); } const encryptedDexieStorage = wrappedKeyEncryptionCryptoJsStorage({ storage: getRxStorageDexie(), }); async function createDatabase() { const db = await createRxDatabase({ name: DB_NAME, storage: encryptedDexieStorage, password: process.env.RXDB_PASSWORD || "rxdb-password-stub", multiInstance: true, // Set to false if single-window electron app. Check later if multiwindows support needed eventReduce: true, // <- default: true ignoreDuplicate: true, // use to supress error after db delete/recreate on db error }); await createCollections(db); return db; } export default async function getDatabase() { await addDevPlugin(); if (!_getDatabase) _getDatabase = await createDatabase(); return _getDatabase; }