2022-11-26 18:36:55 +00:00
|
|
|
import { cloneDeep } from 'lodash';
|
2023-02-12 20:23:30 +00:00
|
|
|
import { state } from '../db-admin/health-legacy';
|
2022-11-26 18:36:55 +00:00
|
|
|
|
|
|
|
declare global {
|
2022-12-24 15:39:55 +00:00
|
|
|
var localDb: any;
|
2022-11-26 18:36:55 +00:00
|
|
|
var db: any;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const put = async (
|
|
|
|
_id: string,
|
|
|
|
type: string,
|
|
|
|
update: (doc: any) => any,
|
2022-12-24 15:39:55 +00:00
|
|
|
defaultDoc: any,
|
|
|
|
local: boolean = false
|
2022-11-26 18:36:55 +00:00
|
|
|
) => {
|
2022-12-24 15:39:55 +00:00
|
|
|
const targetDb = local ? localDb : db;
|
2022-12-13 19:59:39 +00:00
|
|
|
let current;
|
2023-01-20 20:11:18 +00:00
|
|
|
let putDoc;
|
2022-11-26 18:36:55 +00:00
|
|
|
try {
|
2022-12-24 15:39:55 +00:00
|
|
|
current = await targetDb.get(_id);
|
2022-11-26 18:36:55 +00:00
|
|
|
} catch {
|
|
|
|
current = { _rev: undefined, doc: cloneDeep(defaultDoc) };
|
|
|
|
}
|
|
|
|
try {
|
2023-01-20 20:11:18 +00:00
|
|
|
putDoc = {
|
2022-12-24 15:39:55 +00:00
|
|
|
_id,
|
|
|
|
_rev: current._rev,
|
|
|
|
type,
|
2023-02-12 20:23:30 +00:00
|
|
|
shared: current.shared,
|
|
|
|
origin: current.origin ?? state().remoteUrl,
|
2022-12-24 15:39:55 +00:00
|
|
|
doc: update(current.doc),
|
2023-01-20 20:11:18 +00:00
|
|
|
};
|
|
|
|
await targetDb.put(putDoc);
|
2022-11-26 18:36:55 +00:00
|
|
|
} catch (error: any) {
|
|
|
|
if (error.name === 'conflict') {
|
2023-01-20 20:11:18 +00:00
|
|
|
console.log({ caller: 'db.put', _id, type, putDoc, defaultDoc, error });
|
2022-12-24 15:39:55 +00:00
|
|
|
await put(_id, type, update, defaultDoc, local);
|
2022-11-26 18:36:55 +00:00
|
|
|
} else {
|
2023-01-20 20:11:18 +00:00
|
|
|
console.error({ caller: 'db.put', _id, type, putDoc, defaultDoc, error });
|
2022-11-26 18:36:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-01-20 20:11:18 +00:00
|
|
|
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({
|
2022-11-26 18:36:55 +00:00
|
|
|
startkey: key,
|
2023-02-03 10:59:40 +00:00
|
|
|
endkey,
|
2022-11-26 18:36:55 +00:00
|
|
|
...options,
|
|
|
|
});
|
2023-02-03 10:59:40 +00:00
|
|
|
return allDocs;
|
2022-11-26 18:36:55 +00:00
|
|
|
};
|
|
|
|
|
2022-12-24 15:39:55 +00:00
|
|
|
export const get = async (id: string, local: boolean = false) => {
|
|
|
|
const targetDb = local ? localDb : db;
|
|
|
|
return await targetDb.get(id);
|
2022-11-26 18:36:55 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export const putAll = async (docs: any[]) => {
|
|
|
|
return await db.bulkDocs(docs);
|
|
|
|
};
|