page-cache.js
1.65 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
'use strict';
const cachePage = require('../../config/cache');
const logger = global.yoho.logger;
const _ = require('lodash');
function urlJoin(a, b) {
if (_.endsWith(a, '/') && _.startsWith(b, '/')) {
return a + b.substring(1, b.length);
} else if (!_.endsWith(a, '/') && !_.startsWith(b, '/')) {
return a + '/' + b;
} else {
return a + b;
}
}
module.exports = () => {
return (req, res, next) => {
function onRender() {
let route = req.route ? req.route.path : '';
let appPath = req.app.mountpath;
if (_.isArray(route) && route.length > 0) {
route = route[0];
}
let key = urlJoin(appPath, route.toString()); // route may be a regexp
req.app.set('etag', false);
logger.debug(`route: ${key} cache = ${cachePage[key]}`);
// 如果存在cache配置,并且业务代码中没有设置
if (cachePage[key] && res.get('Cache-Control') !== 'no-cache') {
res.set({
'Cache-Control': 'max-age=' + cachePage[key]
});
res.removeHeader('Pragma');
res.removeHeader('Expires');
} else if (req.get('X-Requested-With') === 'XMLHttpRequest') {
res.set('Cache-Control', 'no-cache');
} else {
res.set({
'Cache-Control': 'no-cache',
Pragma: 'no-cache',
Expires: (new Date(1900, 0, 1, 0, 0, 0, 0)).toUTCString()
});
}
}
res.on('render', onRender);
next();
};
};