Ensure all models are defined and attached before running custom scripts

This commit is contained in:
Ritchie Martori 2015-07-29 15:59:10 -07:00
parent 6c33a60bbc
commit 9f1076e1ed
1 changed files with 24 additions and 11 deletions

View File

@ -30,6 +30,7 @@ module.exports = function execute(app, instructions, callback) {
setupDataSources(app, instructions);
setupModels(app, instructions);
setupMiddleware(app, instructions);
setupComponents(app, instructions);
@ -164,15 +165,38 @@ function setupDataSources(app, instructions) {
function setupModels(app, instructions) {
defineMixins(app, instructions);
defineModels(app, instructions);
attachModelsToApp(app, instructions);
customizeModels(app, instructions);
}
function attachModelsToApp(app, instructions) {
instructions.models.forEach(function(data) {
// Skip base models that are not exported to the app
if (!data.config) return;
debug('Attaching model %s to app', data.name);
app.model(data._model, data.config);
});
}
function customizeModels(app, instructions) {
instructions.models.forEach(function(data) {
var model = data._model;
if (data.sourceFile) {
debug('Loading customization script %s', data.sourceFile);
var code = require(data.sourceFile);
if (typeof code === 'function' && model) {
debug('Customizing model %s', data.name);
code(model);
} else {
debug('Skipping model file %s - `module.exports` is not a function',
data.sourceFile);
}
}
});
}
function defineMixins(app, instructions) {
var modelBuilder = (app.registry || app.loopback).modelBuilder;
var BaseClass = app.loopback.Model;
@ -212,17 +236,6 @@ function defineModels(app, instructions) {
} else {
debug('Creating new model %s %j', name, data.definition);
model = registry.createModel(data.definition);
if (data.sourceFile) {
debug('Loading customization script %s', data.sourceFile);
var code = require(data.sourceFile);
if (typeof code === 'function') {
debug('Customizing model %s', name);
code(model);
} else {
debug('Skipping model file %s - `module.exports` is not a function',
data.sourceFile);
}
}
}
data._model = model;