Search code examples
javascripturl-parametersurl-parsing

Validated URL against an Array of URLPatterns. How?


I've created the example below to illustrate the desired outcome. Is it possible to do the same but against an array of URLPatterns?

// Example URL with two numerical params
const url = "https://example.com/app/api/v1/subscribers/1001/users/2001";

// Example URLPattern with two named groups
// https://web.dev/urlpattern/
// https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API
const urlPattern = new URLPattern({ pathname: "/app/api/v1/subscribers/:subscriberId/users/:userId" });

const urlValidate = urlPattern.test(url); // true
const urlExtract = urlPattern.exec(url); // { subscriberId: "1001", userId: "2001" }

// Debug
console.log("url:", url);
console.log("urlPattern:", urlPattern.pathname);
console.log("urlValidate:", urlValidate);
console.log("urlExtract:", urlExtract.pathname.groups);

// Cast subscriberId as Number
const subscriberId = Number(urlExtract.pathname.groups.subscriberId);
// Cast userId as Number
const userId = Number(urlExtract.pathname.groups.userId);

if(subscriberId && userId) console.log("Params validated for SQL Query.");

console.log("subscriberId:", subscriberId, "userId:", userId);


Solution

  • Are you trying to match the url with the patterns, and get the params from it? If so, you can try to do something like this:

    const patterns = [
      new URLPattern({ pathname: "/app/api/v1/subscribers/:subscriberId/users/:userId" }),
      new URLPattern({ pathname: "/app/api/v1/users/:userId" }),
    ];
    
    function getParams(url) {
      const pattern = patterns.find(p => p.test(url));
      if (pattern) {
        return pattern.exec(url).pathname.groups;
      }
    }
    
    const params = getParams('https://example.com/app/api/v1/subscribers/1001/users/2001');
    
    if (params) {
      console.log(params); // { subscriberId: '1001', userId: '2001' }
    } else {
      console.log('Invalid URL');
    }