index.js 1.67 KB
/**
 * sub app product
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2016/05/06
 */

var _ = require('lodash'),
    express = require('express'),
    path = require('path'),
    hbsEvent = require('../../config/hbsevent');

var app = express();
var router = require('./router');

// set view engin
var doraemon = path.join(__dirname, '../../doraemon/views'); // parent view root

app.disable('x-powered-by');

app.on('mount', function(parent) {
    delete parent.locals.settings; // 不继承父 App 的设置
    Object.assign(app.locals, parent.locals);

    if (router.rootRouter && router.rootRouter.length) {
        let rootPath = '';

        if (app.locals.rootPath && _.isString(app.locals.rootPath)) {
            rootPath = app.locals.rootPath;
        }

        router.rootRouter.forEach(el => {
            let fullPath = rootPath;

            if (el.relatedPath && _.isString(el.relatedPath)) {
                fullPath += el.relatedPath;
            }

            const pathArr = _.compact(fullPath.split('/'));

            parent[el.method](el.path, (req, res, next) => {
                Object.assign(res.locals, {
                    module: pathArr[0] || res.locals.module,
                    page: pathArr[1] || res.locals.page
                });

                return next();
            }, ...el.args);
        });
    }
});

app.use(global.yoho.hbs({
    extname: '.hbs',
    defaultLayout: 'layout',
    layoutsDir: doraemon,
    partialsDir: [path.join(__dirname, 'views/partial')],
    views: path.join(__dirname, 'views/action'),
    helpers: Object.assign(require('./helper'), global.yoho.helpers),
    cb: hbsEvent.cb
}));

// router
app.use(router);

module.exports = app;