I am creating a reusable node.js NavigationController class so I can reuse this in other server side projects If I may need or someone else may find it useful.
Here’s the use case.
var navController = new NavigationController({
routes : {
'/user/:action/:anything' : 'UserController',
'/app/:action' : 'AppController',
'/file/:action' : 'FileController',
'/feedback/:action' : 'FeedbackController',
'/:anything' : 'ErrorController'
},
ErrorController : 'ErrorController'
});
navController.init();
The user upon server request can call this function of that object.
navController.navigate(req, res);
Now this and controllers are being called rightly. The thing under navigate(req, res) function which is a part of calling appropriate controller object based on URL is defined as function named getRouteByPath(path). This private function will get the route and will allow navigate(req, res) function to get controller class name to call.
var getRouteByPath = function(path) {
for(var route in config.routes) {
var routeRegex = '';
var routeParts = route.split('/');
for(var rp = 0; rp < routeParts.length; rp++) {
// checking if route part starts with :
if(routeParts[rp].indexOf(':') === 0) {
// this is "anything" part
routeRegex += '[/]?([A-Za-z0-9]*)';
} else if(routeParts[rp] != "") {
routeRegex += '[/]?' + routeParts[rp];
}
}
var routeRegexResult = path.match(routeRegex);
if(routeRegexResult) {
console.log(routeRegexResult);
return route;
}
}
return null;
};
I am too worried about this function as if this is the right way to do that?
Some flaws:
Why do you use the slash as a character class (
[/])? No need to do that, only in regex literals you’d need to escape it with a backslash (like/\//g). Just use a single “/” instead (new RegExp("/", "g"))..indexOf(<string>)==0does work, but searches the whole string and is not very efficient. Better use startswith, in your caseroutePart.charAt(0)==":"<string>.match(<string>)– I recommend building a newRegExpobject and use.test, as you don’t want to match – there is also no need to build capturing groups, I think, because you only return the route string but no matches (okay, you log them).You want to check if the whole
pathmatches your regexp? Dont forget to add^and$. Your current regex for the AppController also matches a route like/user/app/example.Why is your slash (and only the slash) optional (
/?)? Not only I don’t think this is what you want, but it also opens the doors to catastrophic backtracking when building regexes like/\/?user\/?([A-Za-z0-9]*)\/?([A-Za-z0-9]*)/To escape that, you would need to make the whole group optional:
(?:/([^/]*))?.Also, you should build the regexes only once (on initialisation) and store them in a cache, instead of building them each time you call
getRouteByPath. The compilation of theRegExpis somewhere hidden in your code, although it needs to happen.