From 36a3199b3614bdbe58bc5ebdc76ec580bdfe2e6a Mon Sep 17 00:00:00 2001 From: evlist Date: Mon, 7 Nov 2022 18:20:01 +0100 Subject: [PATCH] Code restructuring for db updates. --- src/db/gpx.ts | 19 ++++++++++--------- src/db/lib.ts | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 9 deletions(-) create mode 100644 src/db/lib.ts 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)}` + ); + } + } +};