Skip to content
This repository has been archived by the owner on Feb 4, 2022. It is now read-only.

Commit

Permalink
fix(with-transaction): throw a useful error on invalid return type
Browse files Browse the repository at this point in the history
  • Loading branch information
mbroadst committed Feb 4, 2019
1 parent 5c84489 commit ae64bb4
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
15 changes: 14 additions & 1 deletion lib/sessions.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const MongoNetworkError = require('./error').MongoNetworkError;
const MongoWriteConcernError = require('./error').MongoWriteConcernError;
const Transaction = require('./transactions').Transaction;
const TxnState = require('./transactions').TxnState;
const isPromiseLike = require('./utils').isPromiseLike;

function assertAlive(session, callback) {
if (session.serverSession == null) {
Expand Down Expand Up @@ -328,7 +329,19 @@ function userExplicitlyEndedTransaction(session) {
function attemptTransaction(session, startTime, fn, options) {
session.startTransaction(options);

return fn(session)
let promise;
try {
promise = fn(session);
} catch (err) {
promise = Promise.reject(err);
}

if (!isPromiseLike(promise)) {
session.abortTransaction();
throw new TypeError('Function provided to `withTransaction` must return a Promise');
}

return promise
.then(() => {
if (userExplicitlyEndedTransaction(session)) {
return;
Expand Down
13 changes: 12 additions & 1 deletion lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,23 @@ function collationNotSupported(server, cmd) {
return cmd && cmd.collation && maxWireVersion(server) < 5;
}

/**
* Checks if a given value is a Promise
*
* @param {*} maybePromise
* @return true if the provided value is a Promise
*/
function isPromiseLike(maybePromise) {
return maybePromise && typeof maybePromise.then === 'function';
}

module.exports = {
uuidV4,
calculateDurationInMs,
relayEvents,
collationNotSupported,
retrieveEJSON,
retrieveKerberos,
maxWireVersion
maxWireVersion,
isPromiseLike
};

0 comments on commit ae64bb4

Please sign in to comment.