Comments (12)
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.
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.
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.
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.
usually compile turns things into regexs though, right?
from path-to-regexp.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/compile
from path-to-regexp.
let me give it a shot, thanks for your help
from path-to-regexp.
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.
thanks, two comments:
- 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,
- is it parseUrl(req).pathname or parseUrl(req.pathname) (for future readers) ?
thanks
from path-to-regexp.
- I don't think so. There's nothing you can do with
null
. What would you expect to happen? - 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.
-
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
-
thanks I might just use req.path, but yeah looks like parseUrl(req).pathname is also correct
cheers
from path-to-regexp.
An empty array is not really valid either, it should also throw there.
from path-to-regexp.
Related Issues (20)
- Publish to NPM HOT 1
- Next dynamic route with spread (...) throws 'Unexpected MODIFIER at 70, expected END' HOT 2
- end option does not work as expected HOT 2
- When parsed to tokens, why are backslashes stripped from pattern? HOT 2
- Invalid regex patterns not properly detected. HOT 2
- Another dumb question: How to run tests? HOT 2
- Erroneous test result. HOT 3
- `?` in optional capture group isn't connected to group in output - named param HOT 11
- SyntaxError: Invalid regular expression: invalid group specifier name HOT 1
- The validate config in options is not work in compile function. HOT 1
- throw new TypeError(`Unexpected ${nextType} at ${index}, expected ${type}`) HOT 3
- How about match an empty array? HOT 2
- Regex for non-negative integers only matches two or more digits HOT 1
- Return the matched path/regex
- Escaping the question mark for a query string throws and error HOT 2
- Checking if a path is a subset of another path HOT 1
- params are being joined without `/` HOT 1
- Issue with converted value used in Next.js rewrite HOT 3
- Contributing named capture groups to pathToRegexp HOT 10
- Expected "id" to be a string error with release 7.0.0 HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from path-to-regexp.