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?