Skip to content

Commit

Permalink
fix: support session: null option for save() to opt out of automatic …
Browse files Browse the repository at this point in the history
…session option with transactionAsyncLocalStorage; backport #14744
  • Loading branch information
vkarpov15 committed Jul 15, 2024
1 parent 3f21bfa commit e909e0b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
5 changes: 3 additions & 2 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -289,9 +289,10 @@ Model.prototype.$__handleSave = function(options, callback) {

const session = this.$session();
const asyncLocalStorage = this[modelDbSymbol].base.transactionAsyncLocalStorage?.getStore();
if (!saveOptions.hasOwnProperty('session') && session != null) {
if (session != null) {
saveOptions.session = session;
} else if (asyncLocalStorage?.session != null) {
} else if (!options.hasOwnProperty('session') && asyncLocalStorage?.session != null) {
// Only set session from asyncLocalStorage if `session` option wasn't originally passed in options
saveOptions.session = asyncLocalStorage.session;
}

Expand Down
13 changes: 12 additions & 1 deletion test/docs/transactions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ describe('transactions', function() {
await Test.createCollection();
await Test.deleteMany({});

const doc = new Test({ name: 'test_transactionAsyncLocalStorage' });
let doc = new Test({ name: 'test_transactionAsyncLocalStorage' });
await assert.rejects(
() => m.connection.transaction(async() => {
await doc.save();
Expand Down Expand Up @@ -473,6 +473,17 @@ describe('transactions', function() {

exists = await Test.exists({ name: 'bar' });
assert.ok(!exists);

doc = new Test({ name: 'test_transactionAsyncLocalStorage' });
await assert.rejects(
() => m.connection.transaction(async() => {
await doc.save({ session: null });
throw new Error('Oops!');
}),
/Oops!/
);
exists = await Test.exists({ _id: doc._id });
assert.ok(exists);
});
});
});

0 comments on commit e909e0b

Please sign in to comment.