From 4276420a533954ecbc8da33b330008e45dbd24e8 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Wed, 13 Mar 2019 18:04:00 +0100 Subject: [PATCH] TxDb.transactionAsync to (await for transactions) (#360) --- packages/db/src/engines/TransactionDb.ts | 22 ++++++++++++++++++++++ packages/db/src/types.ts | 1 + packages/trie-db/src/index.ts | 20 ++++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/packages/db/src/engines/TransactionDb.ts b/packages/db/src/engines/TransactionDb.ts index 79f843717..f4572c8bc 100644 --- a/packages/db/src/engines/TransactionDb.ts +++ b/packages/db/src/engines/TransactionDb.ts @@ -26,6 +26,28 @@ export default class TransactionDb implements TxDb { this.txStarted = false; } + async transactionAsync (fn: () => Promise): Promise { + l.debug(() => ['transactionAsync']); + + try { + this.createTx(); + + const result = await fn(); + + if (result) { + this.commitTx(); + } else { + this.revertTx(); + } + + return result; + } catch (error) { + this.revertTx(); + + throw error; + } + } + transaction (fn: () => T): T { l.debug(() => ['transaction']); diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts index ca92c5711..12f7dcc0c 100644 --- a/packages/db/src/types.ts +++ b/packages/db/src/types.ts @@ -34,5 +34,6 @@ export interface BaseDb { } export interface TxDb extends BaseDb { + transactionAsync (fn: () => Promise): Promise; transaction (fn: () => T): T; } diff --git a/packages/trie-db/src/index.ts b/packages/trie-db/src/index.ts index f6fcef9c6..54b26b37e 100644 --- a/packages/trie-db/src/index.ts +++ b/packages/trie-db/src/index.ts @@ -31,6 +31,26 @@ export default class Trie extends Impl implements TrieDb { l.log(`Created with ${this.codec.type} codec, root ${u8aToHex(this.rootHash, 64)}`); } + async transactionAsync (fn: () => Promise): Promise { + try { + this.createCheckpoint(); + + const result = await this.db.transactionAsync(fn); + + if (result) { + this.commitCheckpoint(); + } else { + this.revertCheckpoint(); + } + + return result; + } catch (error) { + this.revertCheckpoint(); + + throw error; + } + } + transaction (fn: () => T): T { try { this.createCheckpoint();