Skip to content

Commit

Permalink
throw error if calling methods on change stream that errored out
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Aug 29, 2024
1 parent 8667bdb commit 9fa956f
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/cursor/changeStream.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/

const EventEmitter = require('events').EventEmitter;
const MongooseError = require('../error/mongooseError');

/*!
* ignore
Expand All @@ -25,6 +26,7 @@ class ChangeStream extends EventEmitter {
this.bindedEvents = false;
this.pipeline = pipeline;
this.options = options;
this.errored = false;

if (options && options.hydrate && !options.model) {
throw new Error(
Expand All @@ -39,6 +41,7 @@ class ChangeStream extends EventEmitter {
try {
changeStreamThunk((err, driverChangeStream) => {
if (err != null) {
this.errored = true;
this.emit('error', err);
return reject(err);
}
Expand All @@ -49,6 +52,7 @@ class ChangeStream extends EventEmitter {
});
} catch (err) {
syncError = err;
this.errored = true;
this.emit('error', err);
reject(err);
}
Expand Down Expand Up @@ -107,10 +111,16 @@ class ChangeStream extends EventEmitter {
}

hasNext(cb) {
if (this.errored) {
throw new MongooseError('Cannot call hasNext() on errored ChangeStream');
}
return this.driverChangeStream.hasNext(cb);
}

next(cb) {
if (this.errored) {
throw new MongooseError('Cannot call next() on errored ChangeStream');
}
if (this.options && this.options.hydrate) {
if (cb != null) {
const originalCb = cb;
Expand Down Expand Up @@ -141,16 +151,25 @@ class ChangeStream extends EventEmitter {
}

addListener(event, handler) {
if (this.errored) {
throw new MongooseError('Cannot call addListener() on errored ChangeStream');
}
this._bindEvents();
return super.addListener(event, handler);
}

on(event, handler) {
if (this.errored) {
throw new MongooseError('Cannot call on() on errored ChangeStream');
}
this._bindEvents();
return super.on(event, handler);
}

once(event, handler) {
if (this.errored) {
throw new MongooseError('Cannot call once() on errored ChangeStream');
}
this._bindEvents();
return super.once(event, handler);
}
Expand Down

0 comments on commit 9fa956f

Please sign in to comment.