import { cloneDeep } from 'lodash'; import { state } from '../db-admin/health-legacy'; import { getParentId } from '../lib/docuri'; 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; let putDoc; try { current = await targetDb.get(_id); } catch { const parentId = getParentId(_id); let to; try { const parent = await db.get(parentId); // console.log({ caller: 'put', parent }); to = parent.to; } catch {} current = { _rev: undefined, to, doc: cloneDeep(defaultDoc) }; } try { putDoc = { _id, _rev: current._rev, type, to: current.to, origin: current.origin ?? state().remoteUrl, doc: update(current.doc), }; await targetDb.put(putDoc); } catch (error: any) { if (error.name === 'conflict') { console.log({ caller: 'db.put', _id, type, putDoc, defaultDoc, error }); await put(_id, type, update, defaultDoc, local); } else { console.error({ caller: 'db.put', _id, type, putDoc, defaultDoc, error }); } } }; export const getFamily = async ( key: string, options: any = {}, local: boolean = false ) => { const targetDb = local ? localDb : db; const endkey = `${key}\ufff0`; const allDocs = await targetDb.allDocs({ startkey: key, endkey, ...options, }); return allDocs; }; 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); };