ssr.js
4.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
const fs = require('fs');
const path = require('path');
const url = require('url');
const _ = require('lodash');
const os = require('os');
const md5 = require('yoho-md5');
const pkg = require('../../package.json');
const routes = require('../../config/ssr-routes');
const redis = require('../../utils/redis');
const routeEncode = require('../../utils/route-encode');
const {createBundleRenderer} = require('vue-server-renderer');
const logger = global.yoho.logger;
const config = global.yoho.config;
const isDev = process.env.NODE_ENV === 'development' || !process.env.NODE_ENV;
let renderer;
let serverBundle;
let degradeHtml;
if (!isDev) {
const template = fs.readFileSync(path.join(__dirname, '../../index.html'), 'utf-8');
degradeHtml = fs.readFileSync(path.join(__dirname, '../../degrade.html'), 'utf-8');
serverBundle = require('../../manifest.server.json');
const clientManifest = require('../../manifest.json');
renderer = createBundleRenderer(serverBundle, {
runInNewContext: false,
template,
clientManifest
});
}
const getContext = (req) => {
return {
url: req.url,
title: '',
user: req.user,
env: {
isApp: req.yoho.isApp,
isiOS: req.yoho.isiOS,
isAndroid: req.yoho.isAndroid,
isYohoApp: req.yoho.isYohoApp,
clientIp: req.yoho.clientIp,
},
ua: req.get('user-agent'),
hostname: os.hostname(),
route: `[${req.method}]${_.get(req, 'route.path', '')}`, // 请求路由
udid: _.get(req, 'cookies.udid', 'yoho'),
path: `[${req.method}]${routeEncode.getRouter(req)}`,
};
};
const handlerError = (err = {}, req, res, next) => {
if (err.code === 404) {
return res.redirect('/error/404');
} else if (err.code === 500) {
return res.redirect('/error/500');
}
return next(err);
};
const getCacheKey = (urlPath, cackeKey = '') => {
const urlObj = url.parse(urlPath);
return md5(cackeKey
.replace('$url', urlObj.pathname)
.replace('$params', urlObj.query));
};
const render = (route) => {
return async(req, res, next) => {
try {
res.set({
'Cache-Control': 'no-cache',
Pragma: 'no-cache',
Expires: (new Date(1900, 0, 1, 0, 0, 0, 0)).toUTCString()
});
res.setHeader('X-YOHO-Version', pkg.version);
const isDegrade = _.get(req.app.locals.wap, 'webapp.degrade', false);
if (isDegrade) {
return res.send(degradeHtml);
}
const ck = route.cackeKey ? getCacheKey(req.url, route.cackeKey) : void 0;
if (config.useCache && route.cache && ck) {
const html = await redis.getAsync(ck);
if (html) {
logger.debug(`cached ${req.url}`);
res.setHeader('X-YOHO-Cached', 'HIT');
return res.send(html);
}
res.setHeader('X-YOHO-Cached', 'MISS');
}
let context = getContext(req);
renderer.renderToString(context, (err, html) => {
if (err) {
return handlerError(err, req, res, next);
}
if (config.useCache && route.cache && ck) {
redis.setex(ck, route.cacheTime || 60, html);
}
return res.send(html);
});
} catch (error) {
return next(error);
}
};
};
const devRender = (route) => {
return async(req, res, next) => {
try {
res.setHeader('X-YOHO-Version', pkg.version);
const ck = route.cackeKey ? getCacheKey(req.url, route.cackeKey) : void 0;
// return require('request-promise')({
// url: 'http://m.yohobuy.com:6005/degrade.html'
// }).pipe(res);
if (config.useCache && route.cache && ck) {
const html = await redis.getAsync(ck);
if (html) {
logger.debug(`cached ${req.url}`);
res.setHeader('X-YOHO-Cached', 'HIT');
return res.send(html);
}
res.setHeader('X-YOHO-Cached', 'MISS');
}
let context = getContext(req);
process.send({action: 'ssr_request', context});
let event = msg => {
process.removeListener('message', event);
if (msg.action === 'ssr_request') {
if (msg.err) {
let err = msg.err;
try {
err = JSON.parse(msg.err);
} catch (error) {} // eslint-disable-line
return handlerError(err, req, res, next);
}
if (config.useCache && route.cache && ck) {
redis.setex(ck, route.cacheTime || 60, msg.html);
}
return res.end(msg.html);
}
};
process.on('message', event);
} catch (error) {
return next(error);
}
};
};
const router = require('express').Router(); //eslint-disable-line
_.each(routes, r => {
if (!r.disable) {
router.get(r.route, isDev ? devRender(r) : render(r));
}
});
exports.ssrRender = isDev ? devRender({}) : render({});
exports.routers = router;