2022-11-26 18:36:55 +00:00
|
|
|
import { cloneDeep } from 'lodash';
|
|
|
|
|
|
|
|
declare global {
|
|
|
|
var db: any;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const put = async (
|
|
|
|
_id: string,
|
|
|
|
type: string,
|
|
|
|
update: (doc: any) => any,
|
|
|
|
defaultDoc: any
|
|
|
|
) => {
|
|
|
|
var current;
|
|
|
|
try {
|
|
|
|
current = await db.get(_id);
|
|
|
|
} catch {
|
|
|
|
current = { _rev: undefined, doc: cloneDeep(defaultDoc) };
|
|
|
|
}
|
|
|
|
try {
|
|
|
|
db.put({ _id, _rev: current._rev, type, doc: update(current.doc) });
|
|
|
|
} catch (error: any) {
|
|
|
|
if (error.name === 'conflict') {
|
2022-12-11 15:20:34 +00:00
|
|
|
console.log({ caller: 'db.put', _id, type, defaultDoc, error });
|
2022-11-26 18:36:55 +00:00
|
|
|
await put(_id, type, update, defaultDoc);
|
|
|
|
} else {
|
2022-12-11 15:20:34 +00:00
|
|
|
console.error({ caller: 'db.put', _id, type, defaultDoc, error });
|
2022-11-26 18:36:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
export const getFamily = async (key: string, options: any = {}) => {
|
|
|
|
return await db.allDocs({
|
|
|
|
startkey: key,
|
|
|
|
endkey: key + '\ufff0',
|
|
|
|
...options,
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
export const get = async (id: string) => {
|
2022-11-28 10:52:50 +00:00
|
|
|
return await db.get(id);
|
2022-11-26 18:36:55 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export const putAll = async (docs: any[]) => {
|
|
|
|
return await db.bulkDocs(docs);
|
|
|
|
};
|