diff --git a/web/database/utils/constants.js b/web/database/utils/constants.js new file mode 100644 --- /dev/null +++ b/web/database/utils/constants.js @@ -0,0 +1,3 @@ +// @flow + +export const SQLITE_CONTENT = 'sqliteFileContent'; 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,6 +1,9 @@ // @flow import localforage from 'localforage'; +import initSqlJs from 'sql.js'; + +import { isDev } from 'lib/utils/dev-utils.js'; import { type SharedWorkerMessageEvent, @@ -10,6 +13,7 @@ workerResponseMessageTypes, type WorkerRequestProxyMessage, } from '../../types/worker-types.js'; +import { SQLITE_CONTENT } from '../utils/constants.js'; const localforageConfig: PartialConfig = { driver: localforage.INDEXEDDB, @@ -20,14 +24,44 @@ }; localforage.config(localforageConfig); -function processAppRequest( +let sqliteDb = null; + +async function initDatabase() { + const content = await localforage.getItem(SQLITE_CONTENT); + + const wasmFilePath = isDev + ? 'http://localhost:3000/comm/compiled' + : 'https://web.comm.app/compiled'; + + const SQL = await initSqlJs({ + locateFile: file => `${wasmFilePath}/${file}`, + }); + + if (content) { + sqliteDb = new SQL.Database(new Uint8Array(content)); + } else { + sqliteDb = new SQL.Database(); + } + + const versionData = sqliteDb.exec('PRAGMA user_version;'); + if (versionData.length && versionData[0].values.length) { + console.info(`Db version: ${versionData[0].values[0]}`); + } else { + throw new Error('Error while retrieving database version'); + } +} + +async function processAppRequest( message: WorkerRequestMessage, -): ?WorkerResponseMessage { +): Promise { if (message.type === workerRequestMessageTypes.PING) { return { type: workerResponseMessageTypes.PONG, text: 'PONG', }; + } else if (message.type === workerRequestMessageTypes.INIT) { + await initDatabase(); + return; } throw new Error('Request type not supported'); @@ -51,7 +85,7 @@ } try { - const result = processAppRequest(message); + const result = await processAppRequest(message); port.postMessage({ id, message: result, diff --git a/web/types/worker-types.js b/web/types/worker-types.js --- a/web/types/worker-types.js +++ b/web/types/worker-types.js @@ -3,6 +3,7 @@ // The types of messages sent from app to worker export const workerRequestMessageTypes = Object.freeze({ PING: 0, + INIT: 1, }); export type PingWorkerRequestMessage = { @@ -10,7 +11,13 @@ +text: string, }; -export type WorkerRequestMessage = PingWorkerRequestMessage; +export type InitWorkerRequestMessage = { + +type: 1, +}; + +export type WorkerRequestMessage = + | PingWorkerRequestMessage + | InitWorkerRequestMessage; export type WorkerRequestProxyMessage = { +id: number,