I have an app with a plugin structure.
I don't know the filepaths of the plugins when starting the app - I look for all valid plugins in the 'plugins' folder. I would like to do the equivalent of this for each plugin:
app.use('/'+ plugin.getPluginName(), plugin.getRoutes());
If I do this in a loop in app.js, the route seems to be added to Express but calls to it result in a 404 error.
I have tried changing the order in which my plugin routes are added to Express, but that didn't work. I have an alternative routing approach working which uses a catch-all routing clause, but I would like to get this working or at least work out what's wrong with this approach.
Here's what I'm doing currently - why doesn't it work?
app.js
var routes = require('./routes/index');
var cards = require('./routes/cards');
var projects = require('./routes/projects');
var app = express();
// Use `.hbs` for extensions
app.engine('hbs', hbs.express3({}));
app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'client')));
// Make our db functionality accessible to our router
app.use(function(req,res,next) {
req.bookshelf = bookshelf;
next();
});
var getPlugins = function(dir, pluginFiles) {
.
.
.
return pluginFiles;
};
var registerPlugins = function() {
var plugins = getPlugins('plugins');
// register plugins and setup databases if required
// set up routing for each plugin
_.each(plugins, function(plugin) {
var p = require('./' + plugin);
p.Plugin.register();
p.Plugin.initRouting(app);
});
};
// set up dbs and register plugins
dbinit.dbInit()
.then(function() {
registerPlugins();
});
app.use('/', routes);
app.use('/cards', cards);
app.use('/projects', projects);
plugin.js
var pluginModels = require('../../../models/plugin'),
_ = require('underscore'),
db = require('./dbinit'),
bookshelf = require('../../../orm');
var express = require('express');
var router = express.Router();
var Pinboard;
Pinboard = pluginModels.Plugin.extend({},{
// register function is in base class
initialize: function () {
},
initDb: function() {
db.dbinit();
},
initRouting: function(app) {
routes = require('./routes');
app.use('/pinboards', routes);
}
});
module.exports = {
Plugin: Pinboard
};
routes.js, in same folder as plugin.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('Get Some Pinboards');
});
module.exports = router;