app.js 1.89 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 bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const {SqlHelper} = require('./utils');

const session = require('yoho-express-session');
const MemcachedStore = require('connect-memcached')(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(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(cookieParser());
app.use(global.yoho.httpCtx());
app.use(session({
    proxy: true,
    resave: false,
    saveUninitialized: true,
    unset: 'destroy',
    secret: 'ekwhekhwkhidfdufy222suqere999',
    name: 'yoho_activity_sid',
    cookie: {
        httpOnly: false
    },
    store: new MemcachedStore({
        hosts: config.memcache.session,
        prefix: 'yoho_activity_sid:',
        reconnect: 5000,
        timeout: 1000,
        retries: 0
    })
}));

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

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

try {

    // 允许跨域
    app.use(cors());

    // 用户信息
    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!');
});