adejs/utils/controllers.js

80 lines
2.4 KiB
JavaScript

const express = require('express');
const fs = require('fs');
const log = require('log');
const pug = require('pug');
const config = require('settings/config');
module.exports = function(app, controllersDir = __dirname + '/../controllers') {
log.debug("Loading controllers :");
let templatesToCompile = [];
let templatesDir = controllersDir + '/../templates';
fs.readdirSync(templatesDir).forEach((templ) => {
templatesToCompile.push(templatesDir + '/' + templ);
});
fs.readdirSync(controllersDir).forEach(function(name) {
// views.js in controller, with function as pages (views.py for django)
let obj = require(controllersDir + '/' + name + '/views');
// urls.js, just like django urls.py
let urls = require(controllersDir + '/' + name + '/urls');
name = obj.name || name;
let templatesDir = controllersDir + '/' + name + '/templates';
fs.readdirSync(templatesDir).forEach((templ) => {
templatesToCompile.push(templatesDir + '/' + templ);
});
// allow specifying the view engine
if (obj.engine) app.set('view engine', obj.engine);
log.debug(' ' + name + ':');
for (let url of urls) {
app[url.method.toLowerCase()](url.url, ((url) => function(req, res, next) {
let path = obj[url.view](req, res, function(template) {
let templatePath = controllersDir + '/' + name + '/templates/' + template;
let renderTime = Date.now();
res.render(templatePath, res.locals, function(err, out) {
log.debug('Template time: ' + (Date.now() - renderTime) + 'ms');
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);
});
if (config.DEBUG === false) {
let time = Date.now();
log.debug('Compiling templates...');
for (let template of templatesToCompile) {
if (template.substr(-4) !== '.txt') {
pug.compileFile(template, {cache: true});
}
}
log.debug("Templates compiled in " + (Date.now() - time) + 'ms');
}
}