You could try a locking mechanism on the database instance to track parallel calls, something like the following:
private depth = 0;
private activeTransactions = 0; // tracks parallel transactions
async transaction<V>(done: (conn: this) => V): Promise<V> {
if (this.activeTransactions > 0 && this.depth === 0) {
//what to do if parallel transaction detected
}
this.activeTransactions += 1;
this.depth += 1;
await this.execute(`SAVEPOINT tt_${this.depth}`);
try {
return await done(this);
} catch (err) {
await this.execute(`ROLLBACK TO tt_${this.depth}`);
throw err;
} finally {
await this.execute(`RELEASE tt_${this.depth}`);
this.depth -= 1;
this.activeTransactions -= 1;
}
}
Alternatively, you could try using a WeakMap
to track concurrent instances or you could use the async-mutex library to do the same thing.