all files / modules/middleware/ rewrite.js

93.33% Statements 14/15
75% Branches 6/8
100% Functions 2/2
93.33% Lines 14/15
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                       12×     12×     12×        
const escapeRegExp = require("../utils/escapeRegExp");
const isRegExp = require("../utils/isRegExp");
const {is} = require("ramda");
/**
 * A middleware that provides URL rewriting behavior similar to Apache's
 * mod_rewrite. The pathname of requests that match the given pattern is
 * overwritten with the replacement using a simple String#replace.
 */
function rewrite(app, pattern, replacement) {
    if (is(String, pattern)) {
        pattern = new RegExp(`^${escapeRegExp(pattern)}$`);
    }
 
    Iif (!isRegExp(pattern)) {
        throw new Error("Rewrite pattern must be a RegExp or String");
    }
 
    replacement = replacement || "";
 
    return function (conn) {
        const pathname = conn.pathname;
 
    // Modify the pathname if the pattern matches.
        if (pattern.test(pathname)) {
            conn.location.properties.pathname = conn.basename + pathname.replace(pattern, replacement);
        }
 
        return conn.call(app);
    };
}
 
module.exports = rewrite;