From 2bb9497f9c903aa1dcdd787776200923b65bf04a Mon Sep 17 00:00:00 2001 From: Mathias Buus Date: Sat, 14 Dec 2024 14:03:40 +0100 Subject: [PATCH] add helper for atomic flows --- index.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/index.js b/index.js index 17f245f..142c8da 100644 --- a/index.js +++ b/index.js @@ -628,6 +628,24 @@ class HypercoreStorage { return new WriteBatch(this, this.db.write(), null) } + // helper for atomic flows + async createWriteBatchAndLock (atomizer, lock) { + assert(this.destroyed === false) + if (atomizer) atomizer.enter() + + try { + await lock.lock() + } catch (err) { + if (atomizer) atomizer.exit() + throw err + } + + const batch = this.createWriteBatch(atomizer) + if (atomizer) atomizer.exit() + + return batch + } + createBlockStream (opts = {}) { assert(this.destroyed === false) return createStream(this, createBlockStream, opts)