Code restructuring for db updates.

This commit is contained in:
Eric van der Vlist 2022-11-07 18:20:01 +01:00
parent 2f362916da
commit 36a3199b36
2 changed files with 42 additions and 9 deletions

View File

@ -1,10 +1,5 @@
import { cloneDeep } from 'lodash';
import getUri from '../lib/ids';
declare global {
var db: any;
var dbReady: boolean;
}
import { put } from './lib';
const emptyGpx: Gpx = {
$: {
@ -38,7 +33,13 @@ const emptyGpx: Gpx = {
export const putNewGpx = (id: string) => {
const uri = getUri('gpx', { gpx: id });
const gpx = cloneDeep(emptyGpx);
gpx.metadata!.time = new Date(Date.now()).toISOString();
db.put({ _id: uri, type: 'gpx', doc: gpx });
put(
uri,
'gpx',
(gpx) => {
gpx.metadata!.time = new Date(Date.now()).toISOString();
return gpx;
},
emptyGpx
);
};

32
src/db/lib.ts Normal file
View File

@ -0,0 +1,32 @@
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') {
await put(_id, type, update, defaultDoc);
} else {
console.error(
`put(${_id}, ${JSON.stringify(
update(current.doc)
)}), error: ${JSON.stringify(error)}`
);
}
}
};