From 87e1e217c3ada7f9baa64e0c012d1b58f0ca3982 Mon Sep 17 00:00:00 2001 From: Raymond Feng Date: Mon, 12 Feb 2018 22:02:17 -0800 Subject: [PATCH] fix: allow `new DataSource(connector, settings)` --- lib/datasource.js | 31 ++++++++++++++++++++++++++----- test/datasource.test.js | 17 +++++++++++++++++ 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/lib/datasource.js b/lib/datasource.js index 1c87400f..71a9ab53 100644 --- a/lib/datasource.js +++ b/lib/datasource.js @@ -89,6 +89,21 @@ var slice = Array.prototype.slice; * @property {String} password Database password. * @property {String} database Name of the database to use. * @property {Boolean} debug Display debugging information. Default is false. + * + * The constructor allows the following styles: + * + * 1. new DataSource(dataSourceName, settings). For example: + * - new DataSource('myDataSource', {connector: 'memory'}); + * - new DataSource('myDataSource', {name: 'myDataSource', connector: 'memory'}); + * - new DataSource('myDataSource', {name: 'anotherDataSource', connector: 'memory'}); + * + * 2. new DataSource(settings). For example: + * - new DataSource({name: 'myDataSource', connector: 'memory'}); + * - new DataSource({connector: 'memory'}); + * + * 3. new DataSource(connectorModule, settings). For example: + * - new DataSource(connectorModule, {name: 'myDataSource}) + * - new DataSource(connectorModule) */ function DataSource(name, settings, modelBuilder) { if (!(this instanceof DataSource)) { @@ -347,11 +362,17 @@ DataSource.prototype.setup = function(dsName, settings) { var dataSource = this; var connector; - // support single settings object - if (dsName && typeof dsName === 'object' && !settings) { - // setup({name: 'myDataSource', connector: 'memory'}) - settings = dsName; - dsName = undefined; + // First argument is an `object` + if (dsName && typeof dsName === 'object') { + if (settings === undefined) { + // setup({name: 'myDataSource', connector: 'memory'}) + settings = dsName; + dsName = undefined; + } else { + // setup(connector, {name: 'myDataSource', host: 'localhost'}) + connector = dsName; + dsName = undefined; + } } if (typeof dsName !== 'string') { diff --git a/test/datasource.test.js b/test/datasource.test.js index 5cb74e0c..b878bbc3 100644 --- a/test/datasource.test.js +++ b/test/datasource.test.js @@ -137,4 +137,21 @@ describe('DataSource', function() { dataSource.name.should.equal('myDataSource'); dataSource.connector.should.equal(mockConnector); }); + + /** + * new DataSource(connectorInstance, settings) + */ + it('should accept resolved connector and settings', function() { + var mockConnector = { + name: 'loopback-connector-mock', + initialize: function(ds, cb) { + ds.connector = mockConnector; + return cb(null); + }, + }; + var dataSource = new DataSource(mockConnector, {name: 'myDataSource'}); + + dataSource.name.should.equal('myDataSource'); + dataSource.connector.should.equal(mockConnector); + }); });