Reputation: 11869
I am in the midst of writing a router that uses a JSON object as a manifest. The router uses the JSON manifest as a reference for where to route incoming requested url paths. The code below belongs to main.js that is ran using the node command to start the application. Near the top of the document, you can see the router object that takes the JSON Manifest as an argument. Below this bit of code, is another bit, that shows the router document where the router class is written into it, you can see there how I am attempting to route request using this JSON Manifest.
const app = require('./serv/katanaLib');
const Router = require('./serv/router');
var router = new Router.Router({
"^/(.*)$" : "/public/view/page/:[?]",
"^/user/(.*)$" : "/public/view/account/:[?]",
"^/style/(.*)$" : "/public/style/:[?]"
});
app.Server(8888, function(request, response)
{
const $_Request = app.parseHttpReq(request);
router.onReq($_Request);
});
module.exports.Router = class Router
{
constructor(JSON_manifest)
{
this.manifest = JSON_manifest;
this.keys = Object.keys(JSON_manifest);
this.values = Object.values(JSON_manifest);
};
onReq($_Request)
{
this.keys.forEach((key, i)=>
{
key = ('^' + key + '$');
var re = new RegExp(key, 'i');
let x = $_Request.path.search(re);
console.log('\n\n' + key);
console.log(re);
console.log(x + '\n\n');
});
};
};
As anyone can obviously see, I am writing Regular Expressions into the keys of the JSON manifest object. You can see that I search the requested path using a foreach loop, looping through each manifest key. The problem I am having is that my regex values are matching multiple times. When I run the code above, and make the follow request to my server.
Request Recieved:
Parsed-Request:
{ path: '/index', method: 'GET', ext: '', type: 'text/html' }
^^/(.*)$$
/^^\/(.*)$$/i
0
^^/user/(.*)$$
/^^\/user\/(.*)$$/i
-1
^^/style/(.*)$$
/^^\/style\/(.*)$$/i
-1
that is a desireable result, but when I run:
i get...
Parsed-Request:
{ path: '/user/abc', method: 'GET', ext: '', type: 'text/html' }
^^/(.*)$$
/^^\/(.*)$$/i
0
^^/user/(.*)$$
/^^\/user\/(.*)$$/i
0
^^/style/(.*)$$
/^^\/style\/(.*)$$/i
-1
The Regular Expression is matching both, the first and second, which is undesirable. If I requested http://localhost/style/123 the requested path will match the first key and third key. If anyone has advice on how to write the regex so I can finish this that would be great, thank you...
Upvotes: 2
Views: 387
Reputation: 1452
To solve the issue with multiple regexes matching, it's best to test them in a specific order, from most specific to least specific. Then, the first match is to be used.
In your example, the regexes are provided as object keys. Since object keys are unordered, you'd need to use an array instead to control the order of the regexes.
In this case, the order of regexes would be as follows (first and second can be swapped):
Upvotes: 1