Skip to content

Commit

Permalink
Merge pull request #14339 from Automattic/IslandRhythms/gh-14330
Browse files Browse the repository at this point in the history
`withSession`
  • Loading branch information
vkarpov15 committed Feb 8, 2024
2 parents 99ad38e + ef5e09e commit 47fad95
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
22 changes: 22 additions & 0 deletions lib/connection.js
Expand Up @@ -443,6 +443,28 @@ Connection.prototype.createCollections = async function createCollections(option
return result;
};

/**
* A convenience wrapper for `connection.client.withSession()`.
*
* #### Example:
*
* await conn.withSession(async session => {
* const doc = await TestModel.findOne().session(session);
* });
*
* @method withSession
* @param {Function} executor called with 1 argument: a `ClientSession` instance
* @return {Promise} resolves to the return value of the executor function
* @api public
*/

Connection.prototype.withSession = async function withSession(executor) {
if (arguments.length === 0) {
throw new Error('Please provide an executor function');
}
return await this.client.withSession(executor);
};

/**
* _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://www.mongodb.com/docs/manual/release-notes/3.6/#client-sessions)
* for benefits like causal consistency, [retryable writes](https://www.mongodb.com/docs/manual/core/retryable-writes/),
Expand Down
12 changes: 12 additions & 0 deletions test/connection.test.js
Expand Up @@ -1553,6 +1553,18 @@ describe('connections:', function() {
});
assert.deepEqual(m.connections.length, 0);
});
it('should demonstrate the withSession() function (gh-14330)', async function() {
if (!process.env.REPLICA_SET && !process.env.START_REPLICA_SET) {
this.skip();
}
const m = new mongoose.Mongoose();
m.connect(start.uri);
let session = null;
await m.connection.withSession(s => {
session = s;
});
assert.ok(session);
});
describe('createCollections()', function() {
it('should create collections for all models on the connection with the createCollections() function (gh-13300)', async function() {
const m = new mongoose.Mongoose();
Expand Down
2 changes: 2 additions & 0 deletions types/connection.d.ts
Expand Up @@ -240,6 +240,8 @@ declare module 'mongoose' {

/** Watches the entire underlying database for changes. Similar to [`Model.watch()`](/docs/api/model.html#model_Model-watch). */
watch<ResultType extends mongodb.Document = any>(pipeline?: Array<any>, options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream<ResultType>;

withSession<T = any>(executor: (session: ClientSession) => Promise<T>): T;
}

}

0 comments on commit 47fad95

Please sign in to comment.