mongoose-transact-utils
Version:
Helper methods for Mongoose and MongoDB transactions
81 lines (63 loc) • 2.2 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var mongoose = _interopDefault(require('mongoose'));
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
/**
* Runs the provided `mutations` callback within a transaction and commits the changes to the DB
* only when it has run successfully.
*
* @param mutations A callback which does DB writes and reads using the session.
*/
function runInTransaction(_x) {
return _runInTransaction.apply(this, arguments);
}
function _runInTransaction() {
_runInTransaction = _asyncToGenerator(function* (mutations) {
const session = yield mongoose.startSession();
session.startTransaction();
try {
const value = yield mutations(session); // Since the mutations ran without an error, commit the transaction.
yield session.commitTransaction(); // Return any value returned by `mutations` to make this function as transparent as possible.
return value;
} catch (error) {
// Abort the transaction as an error has occurred in the mutations above.
yield session.abortTransaction(); // Rethrow the error to be caught by the caller.
throw error;
} finally {
// End the previous session.
session.endSession();
}
});
return _runInTransaction.apply(this, arguments);
}
exports.runInTransaction = runInTransaction;