Blame view

app.js 6.48 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
const helpers = global.yoho.helpers;
shijian authored
38 39
// tdk
global.yoho.redis = require('./doraemon/middleware/redis');
shijian authored
40 41
const tdk = require('./utils/getTDK');
htoooth authored
42 43
// NOTE: 这里修改了图片质量的参数
helpers.image = _.flow(helpers.image, fp.replace(/\/quality\/\d*$/, '/quality/90'));
周少峰 authored
44
htoooth authored
45
// NOTE:这里修改了参数的个数
m  
OF1706 authored
46
helpers.getUrlBySkc = skn => `//item.yohobuy.com/${skn}.html`;
htoooth authored
47
biao authored
48 49
global.middleware = path.resolve('./doraemon/middleware');
global.utils = path.resolve('./utils');
陈轩 authored
50
global.appRoot = path.resolve(__dirname);
biao authored
51
biao authored
52 53
// 向模板注入变量
app.locals.devEnv = app.get('env') === 'development';
yyq authored
54
app.locals.isProduction = app.get('env') === 'production';
biao authored
55 56
app.locals.version = pkg.version;
徐祁xuqi authored
57 58
// zookeeper
if (config.zookeeperServer) {
59
    require('yoho-zookeeper')(config.zookeeperServer, 'pc', app.locals.pc = {}, global.yoho.cache);
徐祁xuqi authored
60 61
}
yyq authored
62 63
app.enable('trust proxy');
姜枫 authored
64
// 请求限制中间件
yyq authored
65 66 67
if (!app.locals.devEnv) {
    app.use(require('./doraemon/middleware/limiter'));
}
姜枫 authored
68
yyq authored
69
app.set('subdomain offset', 2);
OF1706 authored
70 71 72 73

// 添加请求上下文
app.use(global.yoho.httpCtx());
周少峰 authored
74
app.use(global.yoho.hbs({
毕凯 authored
75 76
    extname: '.hbs',
    defaultLayout: 'layout',
周少峰 authored
77 78 79
    layoutsDir: path.join(__dirname, 'doraemon/views'),
    partialsDir: path.join(__dirname, 'doraemon/views/partial'),
    views: path.join(__dirname, 'doraemon/views'),
姜枫 authored
80
    helpers: Object.assign(global.yoho.helpers, require('./utils/helpers'))
毕凯 authored
81
}));
ccbikai authored
82
83
app.use(favicon(path.join(__dirname, '/favicon.ico')));
周少峰 authored
84
app.use(express.static(path.join(__dirname, 'static')));
ccbikai authored
85 86 87
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
徐炜 authored
88
app.use(compression());
毕凯 authored
89
90
app.use(MemcachedSession({  // eslint-disable-line
91 92 93 94 95 96 97 98 99 100 101 102
    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,
周少峰 authored
103
        prefix: config.sessionMemcachedPrefix,
104 105 106 107 108 109
        reconnect: 5000,
        timeout: 1000,
        retries: 0
    })
}));
110
app.use(CookieSession({ // eslint-disable-line
111
    requestKey: 'session2',
112
    cookieName: 'yohobuy_session_cookie',
毕凯 authored
113
    secret: '82dd7e724f2c6870472c89dfa43cf48d',
htoooth authored
114 115 116 117
    cookie: {
        domain: config.cookieDomain,
        ephemeral: true
    }
毕凯 authored
118
}));
ccbikai authored
119
毕凯 authored
120
app.use((req, res, next) => {
121 122 123 124 125 126
    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);
127
128 129 130 131 132 133 134
            _.forEach(differences, d => {
                req.session[d] = req.session2.sessionBack[d];
            });
        }
        req.session2.sessionBack = req.session;
    } else {
        req.session = new MemcachedSession.Session(req);
135 136 137 138
        req.session.cookie = new MemcachedSession.Cookie({
            domain: 'yohobuy.com',
            httpOnly: false
        });
139 140 141 142 143 144 145 146 147 148 149 150 151
        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
152 153
    req.user = {}; // 全局的用户数据
    req.yoho = {}; // req和res绑定yoho对象,用于传递全局数据, 如req.yoho.channel等
毕凯 authored
154
155 156 157 158
    if (!req.session) {
        req.session = {};
    }
159
    // req.app.locals = _.merge(req.app.locals, {
htoooth authored
160 161 162 163 164
    //    pc: {
    //        geetest: {
    //            validation: true
    //        }
    //    }
165
    // });
htoooth authored
166
毕凯 authored
167 168 169
    next();
});
shijian authored
170 171 172
// redis seo
app.use((req, res, next) => {
    if (!req.xhr) {
shijian authored
173
        tdk('url', `${req.hostname}${req.originalUrl}`, req).then(TDKObj =>{
shijian authored
174
            if (TDKObj[0]) {
shijian authored
175 176 177 178 179
                req.tdk = {
                    title: TDKObj[1],
                    keywords: TDKObj[2],
                    description: TDKObj[3]
                };
shijian authored
180 181 182
            }
            next();
        });
shijian authored
183 184
    } else {
        return next();
shijian authored
185 186 187
    }
});
姜枫 authored
188
const logger = global.yoho.logger;
biao authored
189
ccbikai authored
190
// dispatcher
毕凯 authored
191
try {
htoooth authored
192
    const setYohoData = require('./doraemon/middleware/set-yoho-data');
htoooth authored
193
    const htaccess = require('./doraemon/middleware/htaccess');
yyq authored
194
    const subDomain = require('./doraemon/middleware/sub-domain');
yyq authored
195
    const mobileRefer = require('./doraemon/middleware/mobile-refer');
毕凯 authored
196
    const mobileCheck = require('./doraemon/middleware/mobile-check');
毕凯 authored
197 198
    const user = require('./doraemon/middleware/user');
    const seo = require('./doraemon/middleware/seo');
毕凯 authored
199
    const errorHanlder = require('./doraemon/middleware/error-handler');
biao authored
200
    const setPageInfo = require('./doraemon/middleware/set-pageinfo');
姜枫 authored
201
    const layoutTools = require('./doraemon/middleware/layout-tools');
姜枫 authored
202
    const pageCache = require('./doraemon/middleware/page-cache');
徐炜 authored
203
    const devtool = require('./doraemon/middleware/devtools');
毕凯 authored
204 205

    // YOHO 前置中间件
htoooth authored
206
    app.use(setYohoData());
htoooth authored
207
    app.use(htaccess());
yyq authored
208
    app.use(subDomain());
yyq authored
209
    app.use(mobileRefer());
毕凯 authored
210
    app.use(mobileCheck());
毕凯 authored
211 212
    app.use(user());
    app.use(seo());
biao authored
213
    app.use(setPageInfo());
姜枫 authored
214
    app.use(layoutTools());
姜枫 authored
215
    app.use(pageCache());
徐炜 authored
216 217 218 219 220

    if (app.locals.devEnv) {
        app.use(devtool());
    }
毕凯 authored
221 222 223 224 225 226 227 228 229
    require('./dispatch')(app);

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

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

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