pg-promise-scoped-task
v0.0.3
Published
Allows to get currently running transaction. Implementation based on node.js AsyncLocalStorage.
Maintainers
Readme
What it is?
Little helper class that is allowing to use pg-promise transactions created with https://vitaly-t.github.io/pg-promise/Database.html#tx without need to passing around transaction object. This is done with AsyncLocalStorage from node:async_hooks.
How to use it?
import { PGPromiseScopedTask } from "pg-promise-scoped-task";
class SomeService {
constructor(
private readonly pGPromiseScopedTask: PGPromiseScopedTask,
private readonly someRepository: SomeRepository
) {}
someMethod() {
this.pGPromiseScopedTask.runInScopeOfTransaction(() => {
this.someRepository.callDb();
});
}
}
class SomeRepository {
constructor(private readonly pGPromiseScopedTask: PGPromiseScopedTask) {}
callDb() {
/**
* This run in transaction if it is ran in context of `PGPromiseScopedTask.runInScopeOfTransaction`,
* otherwise this is plain `pg-promise` query.
*/
const db = this.pGPromiseScopedTask.currTransaction();
return db.any("SELECT 1");
}
}