2017-09-23 11:39:42 +02:00
|
|
|
const express = require('express');
|
|
|
|
const fs = require('fs');
|
|
|
|
const log = require('log');
|
2017-09-23 11:02:29 +02:00
|
|
|
|
2017-09-23 11:39:42 +02:00
|
|
|
module.exports = function(app, controllersDir = __dirname + '/../controllers') {
|
2017-09-23 11:02:29 +02:00
|
|
|
|
|
|
|
log.debug("Loading controllers :");
|
|
|
|
|
2017-09-23 11:39:42 +02:00
|
|
|
fs.readdirSync(controllersDir).forEach(function(name) {
|
2017-09-23 11:02:29 +02:00
|
|
|
|
|
|
|
// views.js in controller, with function as pages (views.py for django)
|
2017-09-23 11:39:42 +02:00
|
|
|
let obj = require(controllersDir + '/' + name + '/views');
|
2017-09-23 11:02:29 +02:00
|
|
|
|
|
|
|
// urls.js, just like django urls.py
|
2017-09-23 11:39:42 +02:00
|
|
|
let urls = require(controllersDir + '/' + name + '/urls');
|
2017-09-23 11:02:29 +02:00
|
|
|
name = obj.name || name;
|
|
|
|
|
|
|
|
// allow specifying the view engine
|
|
|
|
if (obj.engine) app.set('view engine', obj.engine);
|
|
|
|
|
|
|
|
log.debug(' ' + name + ':');
|
|
|
|
|
|
|
|
for (let url of urls) {
|
|
|
|
|
2017-09-23 18:20:56 +02:00
|
|
|
app[url.method.toLowerCase()](url.url, ((url) => function(req, res, next) {
|
2017-09-23 11:02:29 +02:00
|
|
|
|
2017-09-23 11:39:42 +02:00
|
|
|
let path = obj[url.view](req, res, function(template) {
|
2017-09-23 11:02:29 +02:00
|
|
|
|
2017-09-23 11:39:42 +02:00
|
|
|
let templatePath = controllersDir + '/' + name + '/templates/' + template;
|
|
|
|
res.render(templatePath, res.locals, function(err, out) {
|
2017-09-23 11:02:29 +02:00
|
|
|
if (err !== null) {
|
|
|
|
log.pugerror(err);
|
|
|
|
}
|
|
|
|
res.send(out);
|
|
|
|
});
|
|
|
|
|
|
|
|
}, next);
|
|
|
|
|
|
|
|
})(url));
|
|
|
|
|
|
|
|
log.debug(' ' + url.url + ' -> ' + name + '.' + url.view);
|
|
|
|
}
|
|
|
|
|
|
|
|
log.debug();
|
|
|
|
|
|
|
|
// mount the app
|
|
|
|
// parent.use(app);
|
|
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
}
|