I have 2 services, each has its own transaction block like this:
function tranA() {
const session = await this.connection.startSession();
try {
session.startTransaction();
// Query with the session
await session.commitTransaction();
} catch {
await session.abortTransaction();
} finally {
await session.endSession();
}
}
In one controller, I have to call these 2 services, and make sure that they use
the same transaction i.e. same session
. How should I approach this?
My only idea so far is to move the queries into separate functions, then pass
the session
down, like this:
function tranA() {
const session = await this.connection.startSession();
try {
session.startTransaction();
this.A(session)
await session.commitTransaction();
} ...
}
function A(session) {
// Query with the session
}
then in the controller, I create my own session
then call the services.
The biggest problem with this approach is the duplication of method names. Now
many methods will have 2 versions, one with external session, one with its own
session.