route-encode.js
790 Bytes
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
const _ = require('lodash');
const crypto = global.yoho.crypto;
function urlJoin(a, b) {
return _.trimEnd(a, '/') + '/' + _.trimStart(b, '/');
}
function _encode(str) {
return encodeURIComponent(crypto.encryption(null, str));
}
const encode = _.memoize(_encode);
function getRouter(req) {
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
if (key) {
return encode(key);
}
return '';
}
module.exports.md = function(req, res, next) {
function onRender() {
res.locals._router = getRouter(req);
}
res.on('beforeRender', onRender);
next();
};
module.exports.getRouter = getRouter;