Fix loading of loopback dependencies.

Loopback-explorer loads express and strong-remoting from loopback's
`node_modules` folder. This fails when one of those dependencies
was installed to the parent project, e.g. as a peer dependency.

    app/node_modules
     +- express # <- express installed as peer to loopback
     +- loopback
         +- node_modules # <- express is not there

As of this commit, loopback-explorer will retry the `require()` call
without `loopback/node_modules` prefix if the first require fails.

    1. `require('loopback/node_modules/express')`
    2. `require('express')`

The change should fix (some of) unit-tests failures in
  https://github.com/strongloop/loopback-workspace
This commit is contained in:
Miroslav Bajtos 2013-12-09 11:27:38 +01:00
parent f872275e10
commit eb06404157
1 changed files with 23 additions and 2 deletions

View File

@ -3,8 +3,8 @@
*/
var path = require('path');
var loopback = require('loopback');
var swagger = require('loopback/node_modules/strong-remoting/ext/swagger');
var express = require('loopback/node_modules/express');
var swagger = requireLoopbackDependency('strong-remoting/ext/swagger');
var express = requireLoopbackDependency('express');
var STATIC_ROOT = path.join(__dirname, 'public');
module.exports = explorer;
@ -30,3 +30,24 @@ function explorer(loopbackApplication, options) {
app.use(loopback.static(STATIC_ROOT));
return app;
}
function requireLoopbackDependency(module) {
try {
return require('loopback/node_modules/' + module);
} catch (err) {
if (err.code !== 'MODULE_NOT_FOUND') throw err;
try {
// Dependencies may be installed outside the loopback module,
// e.g. as peer dependencies. Try to load the dependency from there.
return require(module);
} catch (errPeer) {
if (errPeer.code !== 'MODULE_NOT_FOUND') throw errPeer;
// Rethrow the initial error to make it clear that we were trying
// to load a module that should have been installed inside
// "loopback/node_modules". This should minimise end-user's confusion.
// However, such situation should never happen as `require('loopback')`
// would have failed before this function was even called.
throw err;
}
}
}