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);
});
// attach models to dataSources by type
loopback.autoAttach();
// require directories
var requiredModels = requireDir(path.join(appRootDir, 'models'));
}

View File

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