all files / blackbird/modules/utils/ compileRoute.js

100% Statements 12/12
100% Branches 4/4
100% Functions 2/2
100% Lines 12/12
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                         14× 29× 11× 11× 18×   12×     14×      
const paramMatcher = /:([a-zA-Z_$][a-zA-Z0-9_$]*)|[*.()\[\]\\+|{}^$]/g;
 
/**
 * Compiles the given route string into a RegExp that can be used to
 * match a URL. The route may contain named parameters in the form of
 * a colon followed by a valid JavaScript identifier (e.g. ":name",
 * ":_name", and ":$name" are all valid parameters). The route may
 * also contain a * to match any character non-greedily, or a ? to
 * match the previous thing 0 or 1 time.
 *
 * The keys array is populated with names of all parameters in the
 * order they appear in the route string.
 */
function compileRoute(route, keys) {
    const source = route.replace(paramMatcher, function (match, key) {
        if (key) {
            keys.push(key);
            return "([^./?#]+)";
        } else if (match === "*") {
            keys.push("splat");
            return "(.*?)";
        }
        return `\\${match}`;
    });
 
    return new RegExp(`^${source}$`, "i");
}
 
module.exports = compileRoute;