diff --git a/lib/data-service.js b/lib/data-service.js index d01481e..a1f7e59 100644 --- a/lib/data-service.js +++ b/lib/data-service.js @@ -582,6 +582,10 @@ class DataService extends EventEmitter { return this.client.killSession(...args); } + isConnected() { + return this.client.isConnected(); + } + /** * When Node supports ES6 default values for arguments, this can go away. * diff --git a/lib/native-client.js b/lib/native-client.js index c0ad49d..b5e6f11 100644 --- a/lib/native-client.js +++ b/lib/native-client.js @@ -101,6 +101,13 @@ class NativeClient extends EventEmitter { this._isConnected = false; } + isConnected() { + // This is better than just returning internal `_isConnected` as this + // actually shows when the client is available on the NativeClient instance + // and connected + return !!(this.client && this.client.isConnected()); + } + /** * Connect to the server. * @@ -547,6 +554,15 @@ class NativeClient extends EventEmitter { * @param {Function} callback */ disconnect(callback) { + // This follows MongoClient behavior where calling `close` on client that is + // not connected + if (!this.client) { + setImmediate(() => { + callback(); + }); + return; + } + this.client.close(true, err => { if (this.tunnel) { debug('mongo client closed. shutting down ssh tunnel'); diff --git a/test/data-service.test.js b/test/data-service.test.js index 4031009..ddb8260 100644 --- a/test/data-service.test.js +++ b/test/data-service.test.js @@ -17,6 +17,40 @@ describe('DataService', function() { service.disconnect(done); }); + // Each test gets its own service so that we can connect/disconnect it freely + describe('#isConnected', () => { + let _service; + + it('returns false when not connected initially', () => { + _service = new DataService(helper.connection); + expect(_service.isConnected()).to.equal(false); + }); + + it('returns true if client is connected', (done) => { + _service = new DataService(helper.connection); + _service.connect(() => { + expect(_service.isConnected()).to.equal(true); + done(); + }); + }); + + it('returns false if client is disconnected', (done) => { + _service = new DataService(helper.connection); + _service.connect(() => { + _service.disconnect(() => { + expect(_service.isConnected()).to.equal(false); + done(); + }); + }); + }); + + afterEach((done) => { + if (_service) { + _service.disconnect(done); + } + }); + }); + describe('#deleteOne', function() { it('deletes the document from the collection', function(done) { service.insertOne(