From c83f82d5a0d3d8c6165b63608f460881c5e6cee0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20Bajto=C5=A1?= Date: Tue, 21 Apr 2020 14:11:50 +0200 Subject: [PATCH] feat: implement DataSource.stop() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implement `stop` as an alias for `disconnect`. This way LB4 applications don't have to include custom `stop` implementation in every datasource file. Signed-off-by: Miroslav Bajtoš --- lib/datasource.js | 8 ++++++++ test/datasource.test.js | 25 +++++++++++++++++++++++++ types/datasource.d.ts | 3 +++ 3 files changed, 36 insertions(+) diff --git a/lib/datasource.js b/lib/datasource.js index 64ec82ba..82b09cee 100644 --- a/lib/datasource.js +++ b/lib/datasource.js @@ -2220,6 +2220,14 @@ DataSource.prototype.disconnect = function disconnect(cb) { return cb.promise; }; +/** + * An alias for `disconnect` to make the datasource a LB4 life-cycle observer. + * Please note that we are intentionally not providing a `start` method, + * because the logic for establishing connection(s) is more complex + * and usually started immediately from the datasoure constructor. + */ +DataSource.prototype.stop = DataSource.prototype.disconnect; + /** * Copy the model from Master. * @param {Function} Master The model constructor diff --git a/test/datasource.test.js b/test/datasource.test.js index 0d47b9bc..b3127d02 100644 --- a/test/datasource.test.js +++ b/test/datasource.test.js @@ -330,6 +330,31 @@ describe('DataSource', function() { }); }); + it('provides stop() API calling disconnect', function(done) { + const mockConnector = { + name: 'loopback-connector-mock', + initialize: function(ds, cb) { + ds.connector = mockConnector; + process.nextTick(function() { + cb(null); + }); + }, + }; + + const dataSource = new DataSource(mockConnector); + dataSource.on('connected', function() { + // DataSource is now connected + // connected: true, connecting: false + dataSource.connected.should.be.true(); + dataSource.connecting.should.be.false(); + + dataSource.stop(() => { + dataSource.connected.should.be.false(); + done(); + }); + }); + }); + describe('deleteModelByName()', () => { it('removes the model from ModelBuilder registry', () => { const ds = new DataSource('ds', {connector: 'memory'}); diff --git a/types/datasource.d.ts b/types/datasource.d.ts index 3053baf2..34228b7a 100644 --- a/types/datasource.d.ts +++ b/types/datasource.d.ts @@ -287,6 +287,9 @@ export declare class DataSource extends EventEmitter { // legacy callback style disconnect(callback: Callback): void; + // Only promise variant, callback is intentionally not described. + stop(): Promise; + ping(): Promise; // legacy callback style ping(callback: Callback): void;