Blame view

app.js 5.62 KB
ccbikai authored
1 2 3 4 5
/**
 * yohobuy app
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2016/4/25
 */
周奇琪 authored
6
'use strict';
ccbikai authored
7
姜枫 authored
8 9 10 11
if (process.env.USE_APM === '1' && process.env.NODE_ENV === 'production') {
    require('oneapm');
}
周奇琪 authored
12 13
const config = require('./config/common');
周少峰 authored
14 15 16 17 18 19 20
global.Promise = require('bluebird');

const yohoLib = require('yoho-node-lib');

// 全局注册library
yohoLib.global(config);
毕凯 authored
21
const express = require('express');
徐炜 authored
22
const compression = require('compression');
毕凯 authored
23 24 25 26
const path = require('path');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const favicon = require('serve-favicon');
htoooth authored
27 28
const _ = require('lodash');
const fp = require('lodash/fp');
htoooth authored
29
30 31 32 33
const CookieSession = require('client-sessions');
const MemcachedSession = require('yoho-express-session');
const memcached = require('connect-memcached');
const MemcachedStore = memcached(MemcachedSession);
biao authored
34
const pkg = require('./package.json');
毕凯 authored
35
const app = express();
htoooth authored
36 37 38 39
const helpers = global.yoho.helpers;

// NOTE: 这里修改了图片质量的参数
helpers.image = _.flow(helpers.image, fp.replace(/\/quality\/\d*$/, '/quality/90'));
周少峰 authored
40
htoooth authored
41
// NOTE:这里修改了参数的个数
htoooth authored
42
helpers.getUrlBySkc = pid => `//item.yohobuy.com/p${pid}.html`;
htoooth authored
43
biao authored
44 45
global.middleware = path.resolve('./doraemon/middleware');
global.utils = path.resolve('./utils');
陈轩 authored
46
global.appRoot = path.resolve(__dirname);
biao authored
47
biao authored
48 49 50 51
// 向模板注入变量
app.locals.devEnv = app.get('env') === 'development';
app.locals.version = pkg.version;
徐祁xuqi authored
52 53
// zookeeper
if (config.zookeeperServer) {
54
    require('yoho-zookeeper')(config.zookeeperServer, 'pc', app.locals.pc = {}, global.yoho.cache);
徐祁xuqi authored
55 56
}
yyq authored
57 58
app.enable('trust proxy');
姜枫 authored
59 60 61
// 请求限制中间件
app.use(require('./doraemon/middleware/limiter'));
yyq authored
62
app.set('subdomain offset', 2);
周少峰 authored
63
app.use(global.yoho.hbs({
毕凯 authored
64 65
    extname: '.hbs',
    defaultLayout: 'layout',
周少峰 authored
66 67 68
    layoutsDir: path.join(__dirname, 'doraemon/views'),
    partialsDir: path.join(__dirname, 'doraemon/views/partial'),
    views: path.join(__dirname, 'doraemon/views'),
姜枫 authored
69
    helpers: Object.assign(global.yoho.helpers, require('./utils/helpers'))
毕凯 authored
70
}));
ccbikai authored
71
周少峰 authored
72 73
app.use(global.yoho.middleware());
74
app.use(favicon(path.join(__dirname, '/favicon.ico')));
毕凯 authored
75
app.use(express.static(path.join(__dirname, 'public')));
ccbikai authored
76 77 78
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
徐炜 authored
79
app.use(compression());
毕凯 authored
80
81
app.use(MemcachedSession({  // eslint-disable-line
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    proxy: true,
    resave: false,
    saveUninitialized: true,
    unset: 'destroy',
    secret: '82dd7e724f2c6870472c89dfa43cf48d',
    name: 'yohobuy_session',
    cookie: {
        domain: 'yohobuy.com',
        httpOnly: false
    },
    store: new MemcachedStore({
        hosts: config.memcache.session,
        prefix: 'yohobuy_session:',
        reconnect: 5000,
        timeout: 1000,
        retries: 0
    })
}));
101
app.use(CookieSession({ // eslint-disable-line
102
    requestKey: 'session2',
103
    cookieName: 'yohobuy_session_cookie',
毕凯 authored
104
    secret: '82dd7e724f2c6870472c89dfa43cf48d',
htoooth authored
105
    domain: config.cookieDomain
毕凯 authored
106
}));
ccbikai authored
107
毕凯 authored
108
app.use((req, res, next) => {
109 110 111 112 113 114
    if (req.session) {
        let sessionKeys = Object.keys(req.session || {});
        let backSessionKeys = Object.keys(req.session2.sessionBack || {});

        if (backSessionKeys.length > sessionKeys.length) {
            let differences = _.difference(backSessionKeys, sessionKeys);
115
116 117 118 119 120 121 122
            _.forEach(differences, d => {
                req.session[d] = req.session2.sessionBack[d];
            });
        }
        req.session2.sessionBack = req.session;
    } else {
        req.session = new MemcachedSession.Session(req);
123 124 125 126
        req.session.cookie = new MemcachedSession.Cookie({
            domain: 'yohobuy.com',
            httpOnly: false
        });
127 128 129 130 131 132 133 134 135 136 137 138 139
        req.session = _.assign(req.session, req.session2.sessionBack);
    }

    if (typeof req.session.reset !== 'function') {
        req.session.reset = function() {
            req.session = null;
            req.session2.reset();
        };
    }
    next();
});

app.use((req, res, next) => {
毕凯 authored
140 141
    req.user = {}; // 全局的用户数据
    req.yoho = {}; // req和res绑定yoho对象,用于传递全局数据, 如req.yoho.channel等
毕凯 authored
142
143 144 145 146
    if (!req.session) {
        req.session = {};
    }
毕凯 authored
147 148 149
    next();
});
姜枫 authored
150
const logger = global.yoho.logger;
biao authored
151
ccbikai authored
152
// dispatcher
毕凯 authored
153
try {
htoooth authored
154
    const setYohoData = require('./doraemon/middleware/set-yoho-data');
htoooth authored
155
    const htaccess = require('./doraemon/middleware/htaccess');
yyq authored
156
    const subDomain = require('./doraemon/middleware/sub-domain');
yyq authored
157
    const mobileRefer = require('./doraemon/middleware/mobile-refer');
毕凯 authored
158
    const mobileCheck = require('./doraemon/middleware/mobile-check');
毕凯 authored
159 160
    const user = require('./doraemon/middleware/user');
    const seo = require('./doraemon/middleware/seo');
毕凯 authored
161
    const errorHanlder = require('./doraemon/middleware/error-handler');
biao authored
162
    const setPageInfo = require('./doraemon/middleware/set-pageinfo');
姜枫 authored
163
    const layoutTools = require('./doraemon/middleware/layout-tools');
姜枫 authored
164
    const pageCache = require('./doraemon/middleware/page-cache');
徐炜 authored
165
    const devtool = require('./doraemon/middleware/devtools');
毕凯 authored
166 167

    // YOHO 前置中间件
htoooth authored
168
    app.use(setYohoData());
htoooth authored
169
    app.use(htaccess());
yyq authored
170
    app.use(subDomain());
yyq authored
171
    app.use(mobileRefer());
毕凯 authored
172
    app.use(mobileCheck());
毕凯 authored
173 174
    app.use(user());
    app.use(seo());
biao authored
175
    app.use(setPageInfo());
姜枫 authored
176
    app.use(layoutTools());
姜枫 authored
177
    app.use(pageCache());
徐炜 authored
178 179 180 181 182

    if (app.locals.devEnv) {
        app.use(devtool());
    }
毕凯 authored
183 184 185 186 187 188 189 190 191
    require('./dispatch')(app);

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

    // YOHO 后置中间件
    app.use(errorHanlder.serverError());
} catch (err) {
    logger.error(err);
}
ccbikai authored
192 193

// listener
biao authored
194
app.listen(config.port, function() {
毕凯 authored
195
    logger.info('yohobuy start');
ccbikai authored
196
});