app.js 1.54 KB
/**
 * yoho-activity-platform app
 * @author: leo<qi.li@yoho.cn>
 * @date: 2017/6/23
 */
'use strict';
const cors = require('cors');
const express = require('express');
const config = require('./config');
const bluebird = require('bluebird');
const ynLib = require('yoho-node-lib');
const {SqlHelper} = require('./utils');
const bodyParser = require('body-parser');
const compression = require('compression');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');

let logger;
const app = express();

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

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

app.use(cookieSession({
    name: 'yoho_activity',
    secret: 'activity@yoho',
    maxAge: 24 * 60 * 60 * 1000
}));
app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(cookieParser());
app.use(global.yoho.httpCtx());
app.enable('trust proxy');

const middleware = require('./middleware');

try {

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

    // 用户信息
    app.use(middleware.user);

    // 路由分发
    require('./dispatch')(app);

    // 404处理
    app.use(middleware.error.notFound);

    // 错误处理
    app.use(middleware.error.serverError);

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

app.listen(config.port, function() {
    logger.info('yoho-activity-platform started successfully!');
});