Auto attach all models created

This commit is contained in:
Ritchie Martori 2013-11-19 12:23:02 -08:00
parent 178e5dab30
commit 9db8a7a25f
2 changed files with 24 additions and 8 deletions

View File

@ -218,6 +218,9 @@ app.boot = function(options) {
app.model(key, obj); app.model(key, obj);
}); });
// attach models to dataSources by type
loopback.autoAttach();
// require directories // require directories
var requiredModels = requireDir(path.join(appRootDir, 'models')); var requiredModels = requireDir(path.join(appRootDir, 'models'));
} }

View File

@ -96,6 +96,11 @@ loopback.createDataSource = function (name, options) {
ModelCtor.attachTo(ds); ModelCtor.attachTo(ds);
return ModelCtor; return ModelCtor;
}; };
if(options && options.defaultForType) {
loopback.setDefaultDataSourceForType(options.defaultForType, ds);
}
return ds; return ds;
}; };
@ -110,6 +115,9 @@ loopback.createDataSource = function (name, options) {
loopback.createModel = function (name, properties, options) { loopback.createModel = function (name, properties, options) {
var model = loopback.Model.extend(name, properties, options); var model = loopback.Model.extend(name, properties, options);
// try to attach
loopback.autoAttachModel(model);
return model; return model;
} }
@ -206,20 +214,25 @@ loopback.getDefaultDataSourceForType = function(type) {
loopback.autoAttach = function() { loopback.autoAttach = function() {
var models = this.Model.modelBuilder.models; var models = this.Model.modelBuilder.models;
assert.equal(typeof models, 'object', 'Cannot autoAttach without a models object'); assert.equal(typeof models, 'object', 'Cannot autoAttach without a models object');
var lb = this;
Object.keys(models).forEach(function(modelName) { Object.keys(models).forEach(function(modelName) {
var ModelCtor = models[modelName]; var ModelCtor = models[modelName];
if(ModelCtor.autoAttach) { if(ModelCtor) {
var ds = lb.getDefaultDataSourceForType(ModelCtor.autoAttach); loopback.autoAttachModel(ModelCtor);
}
});
}
assert(ds instanceof DataSource, 'cannot autoAttach model "' + modelName loopback.autoAttachModel = function(ModelCtor) {
if(ModelCtor.autoAttach) {
var ds = loopback.getDefaultDataSourceForType(ModelCtor.autoAttach);
assert(ds instanceof DataSource, 'cannot autoAttach model "' + ModelCtor.modelName
+ '". No dataSource found of type ' + ModelCtor.attachTo); + '". No dataSource found of type ' + ModelCtor.attachTo);
ModelCtor.attachTo(ds); ModelCtor.attachTo(ds);
} }
});
} }
/* /*