Created
August 20, 2023 13:30
-
-
Save vip3r011/a73e127caf45c8ff102b3093a402ad8f to your computer and use it in GitHub Desktop.
Mongoose Transaction wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
this needs replicaSet to work | |
*/ | |
const mongoose = require('mongoose'); | |
async function runTransaction(transactionFunction, ...args) { | |
let session = null; | |
try { | |
session = await mongoose.startSession(); | |
session.startTransaction(); | |
const result = await transactionFunction(...args); | |
await session.commitTransaction(); | |
session.endSession(); | |
return result; | |
} catch (err) { | |
if (session) { | |
await session.abortTransaction(); | |
session.endSession(); | |
} | |
throw err; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment