Angular Reverse Router

A reverse router for client side Angular applications

by kshep92

JavaScript

//API
/*
routeFor(users.index) -> /users/;
routeFor(users.show, {id: 1}) -> /users/1;
routeFor(user.index, {confirmed: true, uname: 'john'}) -> /users/?confirmed=true&uname=john 

*/

var routes = {
	users: {
  	index: "/users/",
    show: "/users/:id",
    edit: "/users/:id/edit/:uname",
  }
}

function routeFor(path, args) {
	var params = path.match(/:[a-zA-Z]+/g);
  var url = null;
  if(params) {//Route parameters present?
  	if(args) { //Are there args?
    	//Parse the string
      if(Object.keys(args).length >= params.length ) {
        url = path;
        params.map(function(val) {
          var _key = val.replace(':', '');
          url = url.replace(val, encodeURIComponent(args[_key]));
        });
    	} else { console.error("Not enough arguments for route: "+path); } //Not enough arguments
    } else console.error("Not enough arguments for route: "+path); //Parameters but no arguments
  } else { //No parameters?
  	if(args) { //args present?
    	var queryString = ""
      Object.keys(args).map(function(val, index) {
        var newParam = '';
        if(index == 0) newParam = "?"+val+"="+args[val];
        else newParam = "&"+val+"="+encodeURIComponent(args[val]);
        queryString += newParam;
      });
      url = path + queryString;
    } else { //No parameters, no args
    	url = path;
    }
  }
  return url;
}

console.debug(routeFor(routes.users.index, {id: 34, uname: 'kevin sheppard'}));