Skip to content
Eric Man edited this page Apr 1, 2015 · 1 revision

Here's a quick-and-dirty isomorphic router that uses route-parser.

var Route = require('route-parser');

class Router {
  constructor() {
    this.routes = [];
    for (var i = 0; i < arguments.length; i++) {
      var route = arguments[i];
      var pattern = route[0];
      var target = route[1];
      this.routes.push({
        route: new Route(pattern), 
        target: target
      });
    }
  }

  resolve(url, findAll) {
    var matches = [];
    for (var i = 0; i < this.routes.length; i++) {
      var route = this.routes[i].route;
      var target = this.routes[i].target;
      var parameters = route.match(url);
      if (parameters) {
        matches.push({
          route: route,
          target: target,
          parameters: parameters
        });
        if (!findAll) {
          return matches;
        }
      }
    }
    return matches;
  }

  reverse(target, parameters) {
    for (var i = 0; i < this.routes.length; i++) {
      if (this.routes[i].target === target) {
        var url = this.routes[i].route.reverse(parameters);
        if (url) {
          return url;
        }
      }
    }
    return null;
  }
}


module.exports = new Router (
  ["/", require('./components/PageProfileList')]
);

#Usage#

Client

var matches = Router.resolve(window.location.pathname);
if (matches.length) {
   var Target = matches[0].target;
   var parameters = matches[0].parameters;
   /* parameters is from the url. target is the right-hand-side in the list of routes when router was initialised, corresponds to matched urls.  */
}

Server

  var matches = Router.resolve(req.url);

  if (!matches.length) {
    res.writeHead(404, { 'Content-type': 'text/plain' });
    res.end("Not found: " + req.url);
  }
  else {
    var Target = matches[0].target;
    var parameters = matches[0].parameters;
    // do some rendering, send data through `res`
  }
Clone this wiki locally