route-encode.js 789 Bytes
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;