Giter VIP home page Giter VIP logo

Comments (12)

blakeembrey avatar blakeembrey commented on August 27, 2024

but this doesn't seem to be working, is my approach backwards?

What isn't working? Can you share some code? Creating a RegExp and using it is the only way to do what I believe you're trying to do.

from path-to-regexp.

ORESoftware avatar ORESoftware commented on August 27, 2024

np thx here is more code

I have these 3 route Express style regexes that are provided to my lib for example:

  excludeRoutes: ['/v1/posts/by_id/:id/add_upvote', '/v1/posts/by_id/:id/remove_upvote','/v1/handle/blacklisted'],

so the pseudo code idea is

if(current path (req.path) matches any item in excludeRoutes list){
    next();
}
else{
    doSomething();
    next();
}

(one possible problem with my approach is that req.path is not the right value to use..perhaps I should be using req.url or req.originalUrl)

here is the logic I use now:

     var excludeRoutes;
     var includeOnlyRoutes;

      //  ....user of lib populates either excludeRoutes or includeRoutes or both

   //  then I do:

        (excludeRoutes || []).forEach(function (routeRegex) {
            excludeRegexes.push(pathToRegexp.compile(routeRegex));
        });

        (includeOnlyRoutes || []).forEach(function (routeRegex) {
            includeOnlyRegexes.push(pathToRegexp.compile(routeRegex));
        });

        var matchesInclude = false;

        if (isIncludeOnly) {
            for (var i = 0; i < includeOnlyRegexes; i++) {
                var regex = includeOnlyRegexes[i];
                if (regex.test(req.path)) {
                    matchesInclude = true;
                    break;
                }
            }
            if(!matchesInclude){

                    logFunction('req with url:', req.path, 'was *skipped* by curtain because it was not *included*.');


                //if we have an include only list, and there is no match - the route is already excluded, don't need to check exclude list
                return next();
            }
        }

        var matchesExclude = false;

        for(var j = 0; j < excludeRegexes; j++){
            var regex = excludeRegexes[j];
            if (regex.test(req.path)) {
                matchesExclude = true;
                break;
            }
        }

        if(matchesExclude){

                logFunction('req with url:', req.path, 'was *skipped* by curtain because it was in the exclude list.');


            return next();
        }


            logFunction('req with url:', req.path, 'was *processed* by curtain.');

from path-to-regexp.

dougwilson avatar dougwilson commented on August 27, 2024

Based on your puesdo-code

if(current path (req.path) matches any item in excludeRoutes list){
    next();
}
else{
    doSomething();
    next();
}

You should be able to get that done with the following:

var parseUrl = require('parseurl') // npm install parseurl
var pathToRegexp = require('path-to-regexp') // npm install path-to-regexp

// ...

var excludeRoutes = ['/v1/posts/by_id/:id/add_upvote', '/v1/posts/by_id/:id/remove_upvote','/v1/handle/blacklisted']

// you can compile the entire list at once
// NOTE I'm not using the compile method, but the main export here

var excludeRoutesRegexp = pathToRegexp(excludeRoutes)

// and now your pseudo code:

if (excludeRoutesRegexp.test(parseUrl(req).pathname)) {
    next();
}
else{
    doSomething();
    next();
}

from path-to-regexp.

blakeembrey avatar blakeembrey commented on August 27, 2024

You don't want to use .compile, you want to create a RegExp from the pathToRegexp function and use that for the test. Check the usage demo in the README: https://github.com/pillarjs/path-to-regexp#usage.

Generally, it's a lot easier for people to help if you can narrow down the code sample to the issue you're having. There are multiple other bugs in the code above that you'll find, but when debugging try to grab some parts you know are consistent and run tests to figure out why something isn't working. For example:

var path = '/x/y'
var regexp = pathToRegexp.compile(path)

console.log(regexp) // Whoops, not a regexp.

Edit: I see Doug's beat me to it.

from path-to-regexp.

ORESoftware avatar ORESoftware commented on August 27, 2024

usually compile turns things into regexs though, right?

from path-to-regexp.

ORESoftware avatar ORESoftware commented on August 27, 2024

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/compile

from path-to-regexp.

ORESoftware avatar ORESoftware commented on August 27, 2024

let me give it a shot, thanks for your help

from path-to-regexp.

blakeembrey avatar blakeembrey commented on August 27, 2024

That's a method on the global RegExp object, lots of libraries expose a compile method for doing whatever it is the library does. In this case, it's used to generate a function for compiling Express-style paths into regular paths with the values interpolated.

I'll close this as it seems resolved, but please feel free to continue commenting.

from path-to-regexp.

ORESoftware avatar ORESoftware commented on August 27, 2024

thanks, two comments:

  1. when you pass in null/undefined here:

pathToRegexp(excludeRoutes);

throws an error saying can't read length of undefined

so I have to do this:

pathToRegexp(excludeRoutes || []);

but perhaps it should accept null/undefined?

also,

  1. is it parseUrl(req).pathname or parseUrl(req.pathname) (for future readers) ?

thanks

from path-to-regexp.

blakeembrey avatar blakeembrey commented on August 27, 2024
  1. I don't think so. There's nothing you can do with null. What would you expect to happen?
  2. If the pathname is already available, use that. No need to parse twice. If it's purely Express, you can use req.path. If it's meant as generic middleware, you can parse the request to get the path.

from path-to-regexp.

ORESoftware avatar ORESoftware commented on August 27, 2024
  1. well, what do you do with an empty array for instance? I don't know. IMO you should do same for empty array as for null, but right now null throws an error, because there is no length of null, so I think you have to check for null and not throw an error and just do whatever you do for empty array

  2. thanks I might just use req.path, but yeah looks like parseUrl(req).pathname is also correct

cheers

from path-to-regexp.

blakeembrey avatar blakeembrey commented on August 27, 2024

An empty array is not really valid either, it should also throw there.

from path-to-regexp.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.