Blog>
Snippets

Negation Path Matcher

Create a custom route matcher that excludes certain paths by implementing negation logic.
function negationPathMatcher(path, excludedPaths) {
    // Convert excluded paths to regular expressions, prefixing each path with '^'
    // to ensure the match is from the beginning of the path
    var excludedPatterns = excludedPaths.map(p => new RegExp('^' + p));

    // Check if path matches any of the excluded patterns
    // If it does, the path is negated
    for (var i = 0; i < excludedPatterns.length; i++) {
        if (excludedPatterns[i].test(path)) {
            return false;
        }
    }

    // If the path does not match any excluded patterns, it is not negated
    return true;
}
The function negationPathMatcher takes a path and an array of excluded paths as arguments. It converts the excluded paths into regular expressions, and then checks if the provided path matches any of the excluded patterns. If it matches, the path is rejected (returns false); if not, it is accepted (returns true).
// Usage example
var isAllowed = negationPathMatcher('/some/path', ['/excluded', '/another/excluded']);
console.log(isAllowed); // Output will be true if '/some/path' is not in the excluded paths
Here's an example of how to use the negationPathMatcher function. It is used here to check if the path '/some/path' is allowed by making sure it is not in the list of excluded paths (['/excluded', '/another/excluded']). It logs the result to the console.