import { cloneDeep } from 'lodash'; declare global { var localDb: any; var db: any; } export const put = async ( _id: string, type: string, update: (doc: any) => any, defaultDoc: any, local: boolean = false ) => { const targetDb = local ? localDb : db; let current; try { current = await targetDb.get(_id); } catch { current = { _rev: undefined, doc: cloneDeep(defaultDoc) }; } try { 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, local); } else { console.error({ caller: 'db.put', _id, type, defaultDoc, error }); } } }; export const getFamily = async (key: string, options: any = {}) => { return await db.allDocs({ startkey: key, endkey: key + '\ufff0', ...options, }); }; 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[]) => { return await db.bulkDocs(docs); };