dyomedea/src/db/lib.ts

78 lines
1.8 KiB
TypeScript
Raw Normal View History

import { cloneDeep } from 'lodash';
2023-02-12 20:23:30 +00:00
import { state } from '../db-admin/health-legacy';
import { getParentId } from '../lib/docuri';
2023-03-06 20:38:50 +00:00
import { dbUrlToUserId } from '../lib/user-id';
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;
2022-12-13 19:59:39 +00:00
let current;
let putDoc;
try {
current = await targetDb.get(_id);
} catch {
const parentId = getParentId(_id);
2023-03-04 14:13:27 +00:00
let to;
try {
const parent = await db.get(parentId);
// console.log({ caller: 'put', parent });
2023-03-04 14:13:27 +00:00
to = parent.to;
} catch {}
2023-03-04 14:13:27 +00:00
current = { _rev: undefined, to, doc: cloneDeep(defaultDoc) };
}
try {
putDoc = {
_id,
_rev: current._rev,
type,
2023-03-04 14:13:27 +00:00
to: current.to,
origin:
current.origin ??
(state().remoteUrl ? dbUrlToUserId(state().remoteUrl) : undefined),
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
) => {
2022-12-25 15:30:47 +00:00
const targetDb = local ? localDb : db;
2023-02-03 10:59:40 +00:00
const endkey = `${key}\ufff0`;
const allDocs = await targetDb.allDocs({
startkey: key,
2023-02-03 10:59:40 +00:00
endkey,
...options,
});
2023-02-03 10:59:40 +00:00
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);
};