Creating a second PouchDB database for local (non sync'ed) documents such as state.

This commit is contained in:
Eric van der Vlist 2022-12-24 16:39:55 +01:00
parent cef7431012
commit 0e2ffb0cf2
3 changed files with 25 additions and 9 deletions

View File

@ -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;

View File

@ -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[]) => {

View File

@ -10,7 +10,7 @@ interface State {
export const getState = async <State>() => {
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 <State>() => {
};
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';
};