Skip to content
Merged
Show file tree
Hide file tree
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
24 changes: 24 additions & 0 deletions 3.0-RELEASE-NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,27 @@ All breaking changes must be described here. When adding a new entry,
always describe the impact on users and instructions for upgrading
applications from 2.x to 3.0.

## boot.compile is now async and returns context with instructions

Users that uses `boot.compile()` in the following syntax would need to update
their implementation, it now calls callback function with `instructions` in
`context` object rather than synchronously returning instructions.

Before:

```js
var APP_PATH = path.resolve('../sandbox');
var instructions = boot.compile(APP_PATH);
```

New signature:

```js
var APP_PATH = path.resolve('../sandbox');
var instructions;
boot.compile(APP_PATH, function(err, context) {
instructions = context.instructions;
});
```

Please see [PR #181](https://github.com/strongloop/loopback-boot/pull/181) for full details of change.
19 changes: 13 additions & 6 deletions browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

var execute = require('./lib/executor');
var Bootstrapper = require('./lib/bootstrapper');

/**
* The browser version of `bootLoopBackApp`.
Expand All @@ -21,17 +21,24 @@ var execute = require('./lib/executor');
* @header boot(app)
*/

exports = module.exports = function bootBrowserApp(app, options) {
exports = module.exports = function bootBrowserApp(app, options, callback) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is for LoopBack Next, can we drop support for callbacks and switch exclusively to Promise-based APIs here in loopback-boot?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I want to do this incrementally. The current implementation is ready for LoopBack 3.0. We can further clean it up for LoopBack.next if we decide to drop callback style.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense.

// Only using options.id to identify the browserified bundle to load for
// this application. If no Id was provided, load the default bundle.
var moduleName = 'loopback-boot#instructions';
if (options && typeof options === 'object' && options.appId)
moduleName += '-' + options.appId;
var appId = options && typeof options === 'object' && options.appId;
if (appId)
moduleName += '-' + appId;

// The name of the module containing instructions
// is hard-coded in lib/bundler
var instructions = require(moduleName);
execute(app, instructions);

var bootstrapper = new Bootstrapper(options);
bootstrapper.phases = ['starting', 'start', 'started'];
var context = {
app: app,
instructions: instructions,
};
return bootstrapper.run(context, callback);
};

exports.execute = execute;
58 changes: 42 additions & 16 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,11 @@
// License text available at https://opensource.org/licenses/MIT

// Strong globalize
var SG = require('strong-globalize');
SG.SetRootDir(__dirname);
var g = require('./lib/globalize');

var ConfigLoader = require('./lib/config-loader');
var compile = require('./lib/compiler');
var execute = require('./lib/executor');
var PluginBase = require('./lib/plugin-base');
var Bootstrapper = require('./lib/bootstrapper');
var addInstructionsToBrowserify = require('./lib/bundler');
var utils = require('./lib/utils');

/**
* Initialize an application from an options object or
Expand Down Expand Up @@ -147,11 +144,29 @@ var utils = require('./lib/utils');
*/

exports = module.exports = function bootLoopBackApp(app, options, callback) {
if (typeof options === 'function' && callback === undefined) {
callback = options;
options = {};
}
options = options || {};
// backwards compatibility with loopback's app.boot
options.env = options.env || app.get('env');

var instructions = compile(options);
execute(app, instructions, callback);
var bootstrapper = new Bootstrapper(options);

var context = {
bootstrapper: bootstrapper,
app: app,
};

return bootstrapper.run(context, callback);
};

exports.compile = function(options, done) {
var bootstrapper = new Bootstrapper(options);
bootstrapper.phases = ['load', 'compile'];
var context = {};
return bootstrapper.run(context, done);
};

/**
Expand All @@ -164,14 +179,25 @@ exports = module.exports = function bootLoopBackApp(app, options, callback) {
*
* @header boot.compileToBrowserify(options, bundler)
*/
exports.compileToBrowserify = function(options, bundler) {
addInstructionsToBrowserify(compile(options), bundler);
exports.compileToBrowserify = function(options, bundler, done) {
return exports.compile(options, function(err, context) {
if (err) return done(err);
addInstructionsToBrowserify({ instructions: context.instructions },
bundler);
done();
});
};

/* -- undocumented low-level API -- */

exports.ConfigLoader = ConfigLoader;
exports.compile = compile;
exports.execute = execute;
exports.utils = utils;
exports.addInstructionsToBrowserify = addInstructionsToBrowserify;
exports.Bootstrapper = Bootstrapper;
exports.PluginBase = PluginBase;

exports.execute = function(app, instructions, done) {
var bootstrapper = new Bootstrapper(
{ phases: ['starting', 'start', 'started'] });
var context = {
app: app,
instructions: instructions,
};
return bootstrapper.run(context, done);
};
29 changes: 10 additions & 19 deletions intl/en/messages.json
Original file line number Diff line number Diff line change
@@ -1,25 +1,16 @@
{
"ec551b6f2fafd8d40af801ebe5bb09f6": "Discarding {{middleware}} instructions, {{loopback}} client does not support {{middleware}}.",
"1e5fea50eef843cbffd1d438494912c8": "Cannot resolve path \"{0}\"",
"34319676975b1abf107da7a056abb434": "Invalid normalization format - \"{0}\"",
"46e3ab0ef1149ce0a171b5fac2612ea3": "{{Middleware}} \"{0}\" not found: {1}",
"79e93b2a95e969788590c14e26bb2c1b": "The data in {{model-config.json}} is in the unsupported 1.x format.",
"978a25819e71602cad691dbe7ba17592": "{0} config must be a valid JSON object",
"be2dcdab7aa493ed8d77287eb45cfec8": "cannot require directory contents without directory name",
"2634623ad4b2c5902f6c6bb25e68b733": "WARNING: Main {{config}} file \"{0}.json\" is missing",
"3a7049e42006e8bc19e0f4fc8df63b6b": "The `app` is powered by an incompatible loopback version {0}. Supported versions: {1}",
"3f93b626dd9a1c33d67490f6e71018b5": "WARNING: Main config file \"{0}{{.json}}\" is missing",
"4d052d84c8620730afd4a30832f11724": "Cannot configure unknown model {0}",
"4ed668e9187650d898acf97707df445a": "The {{phase}} \"{0}\" is not defined in the main config.",
"6de7e97f033f2cf477297b3d05a93608": "The {{middleware}} \"{0}\" in phase \"{1}\"is not defined in the main config.",
"94a0c7d5ab6462f7892b90c63f316f42": "invalid array: {0}",
"ec34cc58612cb654742e4cd0a57aca78": "Cannot apply {0}: {1}",
"0b91d122f6459c8bbe7865be0936fc4a": "{{app.restBasePath}} is required",
"1cda77c9954be299bb7154f73cb6ab74": "{{instructions.middleware.phases}} must be an {{array}}",
"22549489736fb0d7eba5a4b08977505f": "{{app.host}} must be a {{string}}",
"4c581cc529a7aeda620d5c4b4ef5cfa8": "{{app.restApiRoot}} must start with \"/\"",
"6037512314fac9d12af6c654a3804823": "Built-in model {0} should have been defined",
"69746d336c89bf4bb371a6c2fe56304d": "{0} does not resolve to a valid value, returned as {1}. \"{2}\" must be resolvable in Environment variable or by app.get().",
"6447e6b342a2c51ab0bc53b3cbdf3742": "Ordering conflict: cannot add \"{0}\" after \"{1}\", because the opposite order was already specified",
"70654dc6eb565613a33344efed3de998": "Failed loading boot script: {0}\n{1}",
"b078ccd043437a258581e387f93dc1a5": "The `{{app}}` is powered by an incompatible {{loopback}} version {0}. Supported versions: {1}",
"e8d29edfb313cfe64f5c96cc7d3d5b4b": "When using {{loopback-boot}} with {{loopback}} <1.9, the {{loopback}} module must be available for `{{require('loopback')}}`.",
"f48405e7c61c3d665b601c9ba41da424": "{{app.port}} must be a {{string}} or {{number}}",
"fa2a7d5137c8891693f9515d48f5b7d7": "{{app.restApiRoot}} must be a {{string}}"
"7f7bdcadb75abfef1bd8a126d547dd6d": "{0} does not resolve to a valid value, returned as {1}. \"{2}\" must be resolvable in Environment variable or by {{app.get()}}.",
"91a742b7c3568cf6b6755741a70b3c52": "The {{middleware}} \"{0}\" in {{phase}} \"{1}\"is not defined in the main config.",
"a3aa22086ae4976cd013065c9a3ff81c": "Cannot apply {0}: ",
"be2cf2868ba54624fe38e9908dde5e9e": "The data in {{model-config.json}} is in the unsupported {{1.x}} format.",
"ec551b6f2fafd8d40af801ebe5bb09f6": "Discarding {{middleware}} instructions, {{loopback}} client does not support {{middleware}}.",
"fdc23df1bd0fe55fe3faabcc89ff60f3": "Middleware \"{0}\" not found: {1}"
}
203 changes: 203 additions & 0 deletions lib/bootstrapper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
// Copyright IBM Corp. 2014,2016. All Rights Reserved.
// Node module: loopback-boot
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

var assert = require('assert');
var async = require('async');
var utils = require('./utils');
var path = require('path');
var pluginLoader = require('./plugin-loader');
var debug = require('debug')('loopback:boot:bootstrapper');
var Promise = require('bluebird');

module.exports = Bootstrapper;

function createPromiseCallback() {
var cb;
var promise = new Promise(function(resolve, reject) {
cb = function(err, data) {
if (err) return reject(err);
return resolve(data);
};
});
cb.promise = promise;
return cb;
}

var builtinPlugins = [
'application', 'datasource', 'model', 'mixin',
'middleware', 'component', 'boot-script', 'swagger',
];

var builtinPhases = [
'load', 'compile', 'starting', 'start', 'started',
];

function loadAndRegisterPlugins(bootstrapper, options) {
var loader = pluginLoader(options);
var loaderContext = {};
loader.load(loaderContext);
loader.compile(loaderContext);

for (var i in loaderContext.instructions.pluginScripts) {
bootstrapper.use('/boot/' + i, loaderContext.instructions.pluginScripts[i]);
}
}

/**
* Create a new Bootstrapper with options
* @param options
* @constructor
*/
function Bootstrapper(options) {
this.plugins = [];
options = options || {};

if (typeof options === 'string') {
options = { appRootDir: options };
}

var appRootDir = options.appRootDir = options.appRootDir || process.cwd();
var env = options.env || process.env.NODE_ENV || 'development';

var appConfigRootDir = options.appConfigRootDir || appRootDir;

options.rootDir = appConfigRootDir;
options.env = env;
this.options = options;

this.phases = options.phases || builtinPhases;
this.builtinPlugins = options.plugins || builtinPlugins;
assert(Array.isArray(this.phases), 'Invalid phases: ' + this.phases);
assert(Array.isArray(this.plugins), 'Invalid plugins: ' +
this.builtinPlugins);

var self = this;
self.builtinPlugins.forEach(function(p) {
var factory = require('./plugins/' + p);
self.use('/boot/' + p, factory(options));
});

try {
loadAndRegisterPlugins(self, options);
} catch (err) {
debug('Cannot load & register plugins: %s', err.stack || err);
}
}

/**
* Register a handler to a given path
* @param {String} path
* @param {Function} handler
*/
Bootstrapper.prototype.use = function(path, handler) {
var plugin = {
path: path,
handler: handler,
};
this.plugins.push(plugin);
};

/**
* Get a list of plugins for the given path
* @param {String} path
* @returns {*}
*/
Bootstrapper.prototype.getPlugins = function(path) {
if (path[path.length - 1] !== '/') {
path = path + '/';
}
return this.plugins.filter(function(p) {
return p.path.indexOf(path) === 0;
});
};

/**
* Get a list of extensions for the given path
* @param {String} path
* @returns {*}
*/
Bootstrapper.prototype.getExtensions = function(path) {
if (path[path.length - 1] !== '/') {
path = path + '/';
}
return this.plugins.filter(function(p) {
if (p.path.indexOf(path) === -1) return false;
var name = p.path.substring(path.length);
return name && name.indexOf('/') === -1;
});
};

/**
* Add more phases. The order of phases is decided by the sequence of phase
* names
* @param {String[]} phases An array of phase names
* @returns {String[]} New list of phases
*/
Bootstrapper.prototype.addPhases = function(phases) {
this.phases = utils.mergePhaseNameLists(this.phases, phases || []);
return this.phases;
};

function pluginIteratorFactory(context, phase) {
return function executePluginPhase(plugin, done) {
var result;
if (typeof plugin.handler[phase] !== 'function') {
debug('Skipping %s.%s', plugin.handler.name, phase);
return done();
}
debug('Invoking %s.%s', plugin.handler.name, phase);
try {
if (plugin.handler[phase].length === 2) {
plugin.handler[phase](context, done);
} else {
result = plugin.handler[phase](context);
Promise.resolve(result)
.then(function onPluginPhaseResolved(value) {
done(null, value);
}, function onPluginPhaseRejected(err) {
debug('Unable to invoke %s.%s()', plugin.name, phase, err);
done(err);
});
}
} catch (err) {
debug('Unable to invoke %s.%s()', plugin.name, phase, err);
done(err);
}
};
}

/**
* Invoke the plugins phase by phase with the given context
* @param {Object} context Context object
* @param {Function} done Callback function. If not provided, a promise will be
* returned
* @returns {*}
*/
Bootstrapper.prototype.run = function(context, done) {
if (!done) {
done = createPromiseCallback();
}
var options = this.options;
var appRootDir = options.appRootDir = options.appRootDir || process.cwd();
var env = options.env || process.env.NODE_ENV || 'development';

var appConfigRootDir = options.appConfigRootDir || appRootDir;

options.rootDir = appConfigRootDir;
options.env = env;

context = context || {};

var phases = context.phases || this.phases;
var bootPlugins = this.getExtensions('/boot');
async.eachSeries(phases, function(phase, done) {
debug('Phase %s', phase);
async.eachSeries(bootPlugins, pluginIteratorFactory(context, phase), done);
}, function(err) {
return done(err, context);
});
return done.promise;
};

Loading