create-app.js 3.66 KB
/**
 * yohobuy app
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2016/4/25
 */
'use strict';

const config = require('./config/common');

// use one apm
if (config.useOneapm) {
    require('oneapm');
}

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const favicon = require('serve-favicon');
const yohoLib = require('yoho-node-lib');
const session = require('express-session');
const memcached = require('connect-memcached');
const pkg = require('./package.json');
const devtools = require('./doraemon/middleware/devtools');
const _ = require('lodash');

const uuid = require('uuid');

const MemcachedStore = memcached(session);

// 全局注册library
yohoLib.global(config);

// 指定 doraemon, utils 目录
global.utils = path.resolve('./utils');
global.doraemon = path.resolve('./doraemon');

exports.createApp = async (app) => {
    // 向模板注入变量
    app.locals.devEnv = app.get('env') === 'development';
    app.locals.proEnv = app.get('env') === 'production';
    app.locals.version = pkg.version;



    const logger = global.yoho.logger;

    if (app.locals.devEnv) {
        app.use(devtools());
    }

    
    app.use(global.yoho.hbs({
        extname: '.hbs',
        defaultLayout: 'layout',

        layoutsDir: path.join(__dirname, 'doraemon/views'),
        partialsDir: path.join(__dirname, 'doraemon/views/partial'),
        views: path.join(__dirname, 'doraemon/views'),
        helpers: _.assign(global.yoho.helpers, require('./utils/helpers'))
    }));

    app.use(favicon(path.join(__dirname, '/public/favicon.ico')));
    app.use(express.static(path.join(__dirname, 'public')));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
        extended: true
    }));
    app.use(cookieParser());

    app.use(session({
        proxy: true,
        resave: false,
        saveUninitialized: true,
        unset: 'destroy',
        secret: '82dd7e724f2c6870472c89dfa43cf48d',
        name: 'yohoblk_session',
        cookie: {
            domain: 'yohoblk.com',
            httpOnly: false
        },
        store: new MemcachedStore({
            hosts: config.memcache.session,
            prefix: 'yohoblk_session:'
        })
    }));

    app.use((req, res, next) => {
        req.user = {}; // 全局的用户数据
        req.yoho = {}; // req和res绑定yoho对象,用于传递全局数据, 如req.yoho.channel等

        if (!req.sessionID) {
            req.sessionID = uuid.v4();
        }
        next();
    });

    // dispatcher
    try {
        const user = require('./doraemon/middleware/user');
        const setYohoData = require('./doraemon/middleware/set-yoho-data');
        const errorHanlder = require('./doraemon/middleware/error-handler');
        const setPageInfo = require('./doraemon/middleware/set-pageinfo');
        const ssrApi = require('./doraemon/middleware/ssr-api');
        const layoutTools = require('./doraemon/middleware/layout-tools');


        // YOHO 前置中间件
        app.use(setYohoData());
        app.use(user());
        app.use(setPageInfo());
        app.use(ssrApi());
        app.use(layoutTools());

        await require('./doraemon/middleware/ssr')(app);
        require('./dispatch')(app);

        app.all('*', errorHanlder.notFound()); // 404

        // YOHO 后置中间件
        app.use(errorHanlder.serverError());
    } catch (err) {
        if (err.code === 9999) {
            logger.error(err);
            throw JSON.stringify(err);
        }
        logger.error(err);
    }

    // listener
    app.listen(config.port, function() {
        logger.info(`worker is started at ${config.port}`);
    });
};