app.js 2.64 KB
/**
 * yoho-activity-platform app
 * @author: leo<qi.li@yoho.cn>
 * @date: 2017/6/23
 */
'use strict';
const cors = require('cors');
const path = require('path');
const express = require('express');
const config = require('./config/common');
const bluebird = require('bluebird');
const ynLib = require('yoho-node-lib');
const {SqlHelper, Yoho} = require('./utils');
const bodyParser = require('body-parser');
const compression = require('compression');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const favicon = require('serve-favicon');
const moment = require('moment');
const _ = require('lodash');
const pkg = require('./package.json');

let logger;
const app = express();

app.locals.devEnv = app.get('env') === 'development';
app.locals.isProduction = app.get('env') === 'production';
app.locals.version = pkg.version;
app.locals.startTime = moment().format('YYYYMMDDHH');

// 全局注册library
ynLib.global(config);
logger = global.yoho.logger;

global.Promise = bluebird;
global.yoho.utils = {
    mysqlCli: new SqlHelper(config.mysql.database),
    yoho: Yoho
};

app.use(cookieSession({
    name: 'yoho_activity',
    secret: 'activity@yoho',
    maxAge: 24 * 60 * 60 * 1000
}));
app.use(compression());
app.use(favicon(path.join(__dirname, '/favicon.ico')));
app.use(express.static(path.join(__dirname, 'public/dist')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(cookieParser());
app.use((req, res, next) => {
    req.user = {}; // 全局的用户数据
    req.yoho = {}; // req和res绑定yoho对象,用于传递全局数据

    next();
});
app.use(global.yoho.httpCtx());
app.enable('trust proxy');

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'))
}));


try {

    // 允许跨域
    app.use(cors({
        credentials: true,
        origin: config.corsAllowOrigin
    }));

    const errorHandler = require('./doraemon/middleware/error-handler');
    const devtools = require('./doraemon/middleware/devtools');

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

    require('./dispatch')(app);
    app.all('*', errorHandler.notFound); // 404

    // YOHO 后置中间件
    app.use(errorHandler.serverError);

} catch (err) {
    logger.error(err);
}

app.listen(config.port, function() {
    logger.info(`yoho-activity-platform started successfully, listening on port:${config.port}`);
});