complez
complez

Reputation: 8332

expressjs any way to test if url pattern match in programmatic way?

I want to perform something similar like this for expressjs pattern

isMatch([expressjs_pattern], [path_string])

EX:
isMatch('/users/:userId/roles/:roleCode/$', '/users/123/roles/admin/')
//    result = true

Anyway to do like this?

Upvotes: 1

Views: 882

Answers (2)

Anthony Alexander
Anthony Alexander

Reputation: 1

This is similar to this question. The router object used by your app contains a stack property containing all of the routes in your app and their associated regexp used for matching the routes path. In one of my apps, I use the router object to check if a query parameter named return_to matches any of the paths in my routes like so:

routes.js

const router = express.Router();
// Middleware used to initialize a reference to the router
// in the session object. This allows router paths / regexp to be 
// accessed later in validation / sanitization code.
router.use((req, res, next) => {
    req.session.router = router;
    next();
 });

sanitize_query.js

const { query } = require('express-validator');

async function sanitizeQuery(req, res, next) {
  let validPathsRegExp = [];
  if (req.query.return_to) {
// Test if a regexp property exists based on whether a route 
// property is truthy within each layer of req.session.router.stack.
    req.session.router.stack.forEach(layer => {
      if (layer.route) validPathsRegExp.push(layer.regexp);
    });
    let pathMatched = false;
    await query('return_to')
      .trim()
      .custom(returnTo => {
        for (let regexp of validPathsRegExp) {
          if (regexp.test(req.query.return_to)) {
            pathMatched = true;
            break;
          }
        }
        if (!pathMatched) {
          req.query.return_to = '/items/1';
          req.flash('info', "The page requested before signing in was invalid, so you've been redirected to your items page.")
        }
        return true;
      })
      .customSanitizer(returnTo => {
        if (!pathMatched) returnTo = '/items/1';
        return returnTo;
      })
      .run(req);
  }
  
  next();
 }

module.exports = sanitizeQuery;


Upvotes: 0

Stock Overflaw
Stock Overflaw

Reputation: 3321

As per Express' guide to Routing, in section Route paths (here):

Express uses path-to-regexp for matching the route paths; see the path-to-regexp documentation for all the possibilities in defining route paths.

So you can npm install path-to-regexp and test strings against patterns:

const p2r = require('path-to-regexp');
const regexp = p2r('/users/:userId/roles/:roleCode');
regexp.test('/users/123/roles/admin'); // true

Upvotes: 5

Related Questions