diff --git a/src/db/index.ts b/src/db/index.ts index 30d5b45..dea544c 100644 --- a/src/db/index.ts +++ b/src/db/index.ts @@ -12,6 +12,7 @@ const currentDbDefinition = { }; declare global { + var localDb: any; var db: any; var dbReady: boolean; } @@ -19,10 +20,16 @@ declare global { export const initDb = async (params: any) => { console.log({ caller: 'initDb' }); + if (globalThis.localDb === undefined) { + globalThis.localDb = new PouchDB('$local_dyomedea$', { + auto_compaction: true, + revs_limit: 10, + }); + } + if (globalThis.db === undefined) { globalThis.db = new PouchDB('dyomedea', { auto_compaction: false, - // revs_limit: 10, }); } const db = globalThis.db; diff --git a/src/db/lib.ts b/src/db/lib.ts index c69bb28..abafe73 100644 --- a/src/db/lib.ts +++ b/src/db/lib.ts @@ -1,6 +1,7 @@ import { cloneDeep } from 'lodash'; declare global { + var localDb: any; var db: any; } @@ -8,20 +9,27 @@ export const put = async ( _id: string, type: string, update: (doc: any) => any, - defaultDoc: any + defaultDoc: any, + local: boolean = false ) => { + const targetDb = local ? localDb : db; let current; try { - current = await db.get(_id); + current = await targetDb.get(_id); } catch { current = { _rev: undefined, doc: cloneDeep(defaultDoc) }; } try { - await db.put({ _id, _rev: current._rev, type, doc: update(current.doc) }); + await targetDb.put({ + _id, + _rev: current._rev, + type, + doc: update(current.doc), + }); } catch (error: any) { if (error.name === 'conflict') { console.log({ caller: 'db.put', _id, type, defaultDoc, error }); - await put(_id, type, update, defaultDoc); + await put(_id, type, update, defaultDoc, local); } else { console.error({ caller: 'db.put', _id, type, defaultDoc, error }); } @@ -36,8 +44,9 @@ export const getFamily = async (key: string, options: any = {}) => { }); }; -export const get = async (id: string) => { - return await db.get(id); +export const get = async (id: string, local: boolean = false) => { + const targetDb = local ? localDb : db; + return await targetDb.get(id); }; export const putAll = async (docs: any[]) => { diff --git a/src/db/state.ts b/src/db/state.ts index a1e4f61..d851258 100644 --- a/src/db/state.ts +++ b/src/db/state.ts @@ -10,7 +10,7 @@ interface State { export const getState = async () => { try { - const state = (await get('state')).doc; + const state = (await get('state', true)).doc; console.log({ caller: 'getState', state }); return state; } catch { @@ -19,7 +19,7 @@ export const getState = async () => { }; export const setState = async (state: State) => { - await put('state', 'state', (doc) => state, {}); + await put('state', 'state', (doc) => state, {}, true); console.log({ caller: 'setState', state }); return 'state'; };