diff --git a/src/db/gpx.ts b/src/db/gpx.ts index a5f1574..084451d 100644 --- a/src/db/gpx.ts +++ b/src/db/gpx.ts @@ -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 + ); }; diff --git a/src/db/lib.ts b/src/db/lib.ts new file mode 100644 index 0000000..5dc1a27 --- /dev/null +++ b/src/db/lib.ts @@ -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)}` + ); + } + } +};