app.js 3.51 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');
const Sender = require('influx-batch-sender');
const Redis = require('./utils/redis');


let logger;
const app = express();

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

// config.yohoVerifyUdid = '1a61c0b4db7b6e27999b1237977b5347eb503956'; // 临时用于红包雨的udid

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

// zookeeper
if (config.zookeeperServer) {
    require('yoho-zookeeper')(config.zookeeperServer, 'yap', app.locals.yap = {}, false, {});
}


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

global.yoho.redis = new Redis(config.redis);
global.yoho.sender = new Sender(config.monitorReport); // 初始化数据上报

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对象,用于传递全局数据
    req.cookies.from = 'action';

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

app.use((req, res, next) => {
    req.isApmReport = _.get(req.app.locals, 'isProduction', false);
    next();
});

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 setYohoData = require('./doraemon/middleware/set-yoho-data');
    const errorHandler = require('./doraemon/middleware/error-handler');
    const devtools = require('./doraemon/middleware/devtools');

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

    // docker验证项目是否正常发布
    app.use('/node/status.html', (req, res) => {
        return res.status(200).end();
    });

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