{"size": 1632, "ext": "js", "max_stars_repo_path": "extend/rewriter.js", "max_stars_repo_name": "DynamicAnt/ants-hole", "max_stars_repo_stars_event_min_datetime": "2018-01-25T03:48:15.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-23T06:14:06.000Z", "max_issues_repo_path": "extend/rewriter.js", "max_issues_repo_name": "DynamicAnt/ants-hole", "max_issues_repo_issues_event_min_datetime": "2019-10-31T01:57:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-31T01:59:39.000Z", "max_forks_repo_path": "extend/rewriter.js", "max_forks_repo_name": "DynamicAnt/ants-hole", "max_forks_repo_forks_event_min_datetime": "2018-01-25T02:09:44.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-25T02:09:44.000Z"}
{"max_stars_count": 2, "max_issues_count": 2, "max_forks_count": 1, "avg_line_length": 29.1428571429, "max_line_length": 73, "alphanum_fraction": 0.4736519608}
let url = require('url');
const querystring = require('querystring');
const config = require('../config/rewriter');

let inRules = [];
let outRules = [];

(function () {
    let keys = Object.keys(config);
    keys.forEach(function(key){
        let inRule = config[key].in;
        let outRule = config[key].out;
        inRules.push({
            regexp:new RegExp(inRule.from),
            replace:inRule.to
        });
        outRules.push({
            regexp:new RegExp(outRule.from),
            replace:outRule.to
        })
    });
})();

module.exports = {
    inbound:function(){
        return function rewrite(req,res,next){
            let queryStr = querystring.stringify(req.query);
            let src = url.parse(req.originalUrl);
            let pathname = src.pathname;
            inRules.some(function(rule){
                var ret = false;
                if(rule.regexp.test(pathname)){
                    req.url = pathname.replace(rule.regexp,rule.replace);
                    var str = req.url.match(/(.*)(\?.*)/);
                    if (str) {
                        queryStr = str[2]+'&'+queryStr;
                        req.query = querystring.parse(queryStr);
                    }
                    ret = true;
                }
                return ret;
            });
            next();
        }
    },
    outbound:function(src){
        let ret = src;
        outRules.some(function(rule){
            if (rule && rule.regexp.test(src)) {
                ret = src.replace(rule.regexp, rule.replace);
                return true;
            }
        })
        return ret;
    }
}