Hi there,
With mongoose and express.js, how can I structurally wrap controllers / request handlers in a transaction function of mongoose, so that every controller has a session object to manupulate the DB.
For example, I have a wrapper function that looks something like:
runInTransaction<T>(mutations: CallBackFunc<T>, options : any) {
const session = await mongoose.startSession();
session.startTransaction(options);
try{
const value = await mutation(session);
await session.commitTransaction();
return value;
}
catch(e) {
await session.abortTransaction();
throw e;
}
finally {
session.endSession();
}
}
I’d like to have ALL my controllers to run in this pattern, so that every controller has a session object to pass to services and perform DB manipulation.
How can I do that ?
and is this a good practice ?
Id realy appreciate your input here.
Thanks
Shaun