Skip to content

Commit

Permalink
Merge pull request #14681 from Automattic/vkarpov15/gh-14611
Browse files Browse the repository at this point in the history
feat(connection): bubble up monitorCommands events to Mongoose connection if `monitorCommands` option set
  • Loading branch information
vkarpov15 committed Jun 24, 2024
2 parents 9590792 + 094277f commit da15836
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
6 changes: 6 additions & 0 deletions lib/drivers/node-mongodb-native/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,12 @@ function _setClient(conn, client, options, dbName) {
});
}

if (options.monitorCommands) {
client.on('commandStarted', (data) => conn.emit('commandStarted', data));
client.on('commandFailed', (data) => conn.emit('commandFailed', data));
client.on('commandSucceeded', (data) => conn.emit('commandSucceeded', data));
}

conn.onOpen();

for (const i in conn.collections) {
Expand Down
24 changes: 23 additions & 1 deletion test/connection.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ describe('connections:', function() {
let conn;

before(async function() {
conn = mongoose.createConnection(start.uri2);
conn = mongoose.createConnection(start.uri2, { monitorCommands: true });
await conn.asPromise();
await conn.collection('test').deleteMany({});
return conn;
Expand Down Expand Up @@ -254,6 +254,28 @@ describe('connections:', function() {
assert.equal(events[1].method, 'findOne');
assert.deepStrictEqual(events[1].result, { _id: 17, answer: 42 });
});

it('commandStarted, commandFailed, commandSucceeded (gh-14611)', async function() {
let events = [];
conn.on('commandStarted', event => events.push(event));
conn.on('commandFailed', event => events.push(event));
conn.on('commandSucceeded', event => events.push(event));

await conn.collection('test').insertOne({ _id: 14611, answer: 42 });
assert.equal(events.length, 2);
assert.equal(events[0].constructor.name, 'CommandStartedEvent');
assert.equal(events[0].commandName, 'insert');
assert.equal(events[1].constructor.name, 'CommandSucceededEvent');
assert.equal(events[1].requestId, events[0].requestId);

events = [];
await conn.createCollection('tests', { capped: 1024 }).catch(() => {});
assert.equal(events.length, 2);
assert.equal(events[0].constructor.name, 'CommandStartedEvent');
assert.equal(events[0].commandName, 'create');
assert.equal(events[1].constructor.name, 'CommandFailedEvent');
assert.equal(events[1].requestId, events[0].requestId);
});
});

it('should allow closing a closed connection', async function() {
Expand Down

0 comments on commit da15836

Please sign in to comment.