Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 26 additions & 13 deletions lib/executor.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
var assert = require('assert');
var _ = require('underscore');
var loopback = require('loopback');
var semver = require('semver');
var debug = require('debug')('loopback:boot:executor');

Expand All @@ -14,6 +13,7 @@ var debug = require('debug')('loopback:boot:executor');
*/

module.exports = function execute(app, instructions) {
patchAppLoopback(app);
assertLoopBackVersion(app);

setHost(app, instructions);
Expand All @@ -23,25 +23,38 @@ module.exports = function execute(app, instructions) {

setupDataSources(app, instructions);
setupModels(app, instructions);
autoAttach();
autoAttach(app);

runBootScripts(app, instructions);

enableAnonymousSwagger(app, instructions);
};

function patchAppLoopback(app) {
if (app.loopback) return;
// app.loopback was introduced in 1.9.0
// patch the app object to make loopback-boot work with older versions too
try {
app.loopback = require('loopback');
} catch(err) {
if (err.code === 'MODULE_NOT_FOUND') {
console.error(
'When using loopback-boot with loopback <1.9, '+
'the loopback module must be available for `require(\'loopback\')`.');
}
throw err;
}
}

function assertLoopBackVersion(app) {
var RANGE = '1.x || 2.x';

// app.loopback was introduced in 1.9.0
var loopback = app.loopback || {};
var version = loopback.version || '1.0.0';

if (!semver.satisfies(version, RANGE)) {
var loopback = app.loopback;
if (!semver.satisfies(loopback.version || '1.0.0', RANGE)) {
throw new Error(
'The `app` is powered by an incompatible loopback version %s. ' +
'Supported versions: %s',
loopback.version || '<1.9',
loopback.version || '(unknown)',
RANGE);
}
}
Expand Down Expand Up @@ -134,14 +147,14 @@ function runScripts(app, list) {
if (!list || !list.length) return;
list.forEach(function(filepath) {
var exports = tryRequire(filepath);
if (isFunctionNotModelCtor(exports))
if (isFunctionNotModelCtor(exports, app.loopback.Model))
exports(app);
});
}

function isFunctionNotModelCtor(fn) {
function isFunctionNotModelCtor(fn, Model) {
return typeof fn === 'function' &&
!(fn.prototype instanceof loopback.Model);
!(fn.prototype instanceof Model);
}

function tryRequire(modulePath) {
Expand All @@ -158,9 +171,9 @@ function tryRequire(modulePath) {
}

// Deprecated, will be removed soon
function autoAttach() {
function autoAttach(app) {
try {
loopback.autoAttach();
app.loopback.autoAttach();
} catch(e) {
if(e.name === 'AssertionError') {
console.warn(e);
Expand Down