diff --git a/web/database/utils/constants.js b/web/database/utils/constants.js --- a/web/database/utils/constants.js +++ b/web/database/utils/constants.js @@ -5,8 +5,6 @@ export const CURRENT_USER_ID_KEY = 'current_user_id'; -export const DB_PERSIST_THROTTLE_WAIT_MS = 300; - export const DATABASE_WORKER_PATH = '/worker/database'; export const SQLJS_FILE_PATH = '/compiled/webworkers'; diff --git a/web/database/worker/db-worker.js b/web/database/worker/db-worker.js --- a/web/database/worker/db-worker.js +++ b/web/database/worker/db-worker.js @@ -1,7 +1,6 @@ // @flow import localforage from 'localforage'; -import _throttle from 'lodash/throttle.js'; import initSqlJs, { type SqliteDatabase } from 'sql.js'; import type { @@ -34,7 +33,6 @@ } from '../queries/storage-engine-queries.js'; import { CURRENT_USER_ID_KEY, - DB_PERSIST_THROTTLE_WAIT_MS, SQLITE_CONTENT, SQLITE_ENCRYPTION_KEY, } from '../utils/constants.js'; @@ -56,6 +54,9 @@ let sqliteDb: ?SqliteDatabase = null; let encryptionKey: ?CryptoKey = null; +let persistNeeded: boolean = false; +let persistInProgress: boolean = false; + async function initDatabase(sqljsFilePath: string, sqljsFilename: ?string) { encryptionKey = await localforage.getItem(SQLITE_ENCRYPTION_KEY); if (!encryptionKey) { @@ -133,6 +134,7 @@ } async function persist() { + persistInProgress = true; if (!sqliteDb) { throw new Error('Database not initialized'); } @@ -147,9 +149,14 @@ } const encryptedData = await encryptDatabaseFile(dbData, encryptionKey); await localforage.setItem(SQLITE_CONTENT, encryptedData); -} -const throttledPersist = _throttle(persist, DB_PERSIST_THROTTLE_WAIT_MS); + if (persistNeeded) { + persistNeeded = false; + persist(); + } else { + persistInProgress = false; + } +} async function processAppRequest( message: WorkerRequestMessage, @@ -224,7 +231,14 @@ } if (workerWriteRequests.includes(message.type)) { - throttledPersist(); + if (persistInProgress) { + // persist process is running, it will need to be scheduled again + persistNeeded = true; + } else { + // persist process is not running, scheduling for the first time + persist(); + } + return; }