diff --git a/lib/datasource.js b/lib/datasource.js index 1f3846c5..d710daa5 100644 --- a/lib/datasource.js +++ b/lib/datasource.js @@ -393,7 +393,7 @@ DataSource.prototype.defineRelations = function (modelClass, relations) { // Create a function for the closure in the loop var createListener = function (name, relation, targetModel, throughModel) { if (!isModelDataSourceAttached(targetModel)) { - targetModel.once('dataSourceAttached', function (model) { + targetModel.once('dataAccessConfigured', function (model) { // Check if the through model doesn't exist or resolved if (!throughModel || isModelDataSourceAttached(throughModel)) { // The target model is resolved @@ -410,7 +410,7 @@ DataSource.prototype.defineRelations = function (modelClass, relations) { } if (throughModel && !isModelDataSourceAttached(throughModel)) { // Set up a listener to the through model - throughModel.once('dataSourceAttached', function (model) { + throughModel.once('dataAccessConfigured', function (model) { if (isModelDataSourceAttached(targetModel)) { // The target model is resolved var params = traverse(relations).clone(); @@ -479,9 +479,15 @@ DataSource.prototype.setupDataAccess = function (modelClass, settings) { // add data access objects this.mixin(modelClass); + // define relations from LDL (options.relations) var relations = settings.relationships || settings.relations; this.defineRelations(modelClass, relations); + // Emit the dataAccessConfigured event to indicate all the methods for data + // access have been mixed into the model class + modelClass.emit('dataAccessConfigured', modelClass); + + // define scopes from LDL (options.relations) var scopes = settings.scopes || {}; this.defineScopes(modelClass, scopes); diff --git a/test/loopback-dl.test.js b/test/loopback-dl.test.js index a6f840c3..45d80c18 100644 --- a/test/loopback-dl.test.js +++ b/test/loopback-dl.test.js @@ -350,6 +350,34 @@ describe('DataSource define model', function () { }); + it('should emit events during attach', function() { + var ds = new DataSource('memory'); + var modelBuilder = new ModelBuilder(); + + var User = modelBuilder.define('User', { + name: String + }); + + var seq = 0; + var dataAccessConfigured = -1; + var dataSourceAttached = -1; + + User.on('dataAccessConfigured', function (model) { + dataAccessConfigured = seq++; + assert(User.create); + assert(User.hasMany); + }); + + User.on('dataSourceAttached', function (model) { + assert(User.dataSource instanceof DataSource); + dataSourceAttached = seq++; + }); + + ds.attach(User); + assert.equal(dataAccessConfigured, 0); + assert.equal(dataSourceAttached, 1); + }); + it('should not take unknown properties in strict mode', function (done) { var ds = new DataSource('memory');