TxDb.transactionAsync to (await for transactions) (#360)

This commit is contained in:
Jaco Greeff
2019-03-13 18:04:00 +01:00
committed by GitHub
parent 035960817d
commit 4276420a53
3 changed files with 43 additions and 0 deletions
+22
View File
@@ -26,6 +26,28 @@ export default class TransactionDb implements TxDb {
this.txStarted = false;
}
async transactionAsync<T> (fn: () => Promise<T>): Promise<T> {
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<T> (fn: () => T): T {
l.debug(() => ['transaction']);
+1
View File
@@ -34,5 +34,6 @@ export interface BaseDb {
}
export interface TxDb extends BaseDb {
transactionAsync <T> (fn: () => Promise<T>): Promise<T>;
transaction <T> (fn: () => T): T;
}
+20
View File
@@ -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<T> (fn: () => Promise<T>): Promise<T> {
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<T> (fn: () => T): T {
try {
this.createCheckpoint();