• Stars
    star
    187
  • Rank 206,464 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 11 years ago
  • Updated almost 10 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Trie-based URL Routing

Routington

NPM version Build status Test coverage Dependency Status License Downloads Gittip

Routington is a trie-based URL router. Its goal is only to define and match URLs. It does not handle methods, headers, controllers, views, etc., in anyway. It is faster than traditional, linear, regular expression-matching routers, although insignficantly, and scales with the number of routes.

The purpose of this router isn't for performance, but to bring more structure to URL routing. The intention is for you to build a framework on top either in node.js or in the browser.

Implementations:

API

node Node = Routington()

var routington = require('routington')
var router = routington()

router is the root Node in the trie. All nodes will have router as furthest ancestor.

Node

Every node on a tree is an instance of Node. You only construct the root. A node has the following properties:

  • child {}Node - String based child definitions. For example, node.child['post'] will return a child node with node.string === 'post'
  • children []Node - Name/regex based child definitions
  • parent Node - The parent of the node
  • name - Name of the node (for parameter matching)
  • string - String to match the URL fragment
  • regex - Regular expression to match the URL fragment

nodes []Node = router.define(route)

var nodes = router.define('/:identity(page|petition)/:id([0-9a-f]{24})')
  • route is a definition of a route and is an extension of Express' routing syntax. route, however, can only be a string.
  • nodes is an array of nodes.

Each fragment of the route, delimited by a /, can have the following signature:

  • string - ex /post
  • string|string - | separated strings, ex /post|page
  • :name - Wildcard route matched to a name
  • (regex) - A regular expression match without saving the parameter (not recommended)
  • :name(regex)- Named regular expression match

You should always name your regular expressions otherwise you can't use the captured value. The regular expression is built using new RegExp('^(' + regex + ')$', 'i'), so you need to escape your string, ie \\w. You can always pre-define names or regular expressions before. For example, I can define:

router.define('/page/:id(\\w{3,30})')

// later, :id will have the same regexp
// so you don't have to repeat yourself
router.define('/page/:id/things')

match {} = router.match(url)

router.define('/page/:id(\\w{3,30})')
var match = router.match('/page/taylorswift')

match, unless null, will be an object with the following properties:

  • param - A list of named parameters, ex, match.param.id === 'taylorswift'.
  • node - The matched node. Will always have name.string === ''.

Building a Router on top of Routington

Each URL you define creates a node, and you are free to do whatever you'd like with each node as long you don't overwrite any prototype properties (basically just define, match, and parse). Adding any features to routington shouldn't be necessary.

For example, suppose you want to attach callbacks to a node by extending routington:

router.get('/:id/:controller', function (req, res, next) {
  console.log('do something')
})

You can attach the middleware to a node.GET array:

router.get = function (path, handler) {
  var node = router.define(path)[0]
  node.GET = node.GET || []
  node.GET.push(handler)
}

Now, dispatching is easy:

function dispatcher(req, res, next) {
  var match = router.match(url.parse(req.url).pathname)
  if (!match)
    // this is a 404

  var node = match.node
  var callbacks = node[req.method]
  if (!callbacks)
    // this is a 405

  // execute all the callbacks.
  // async.series won't actually work here,
  // but you get the point.
  async.series(callbacks, next)
}

Properties attached to the node will be exposed on the match. For example, suppose you wanted to label a node:

var node = router.define('/:id/:controller')[0]
node.label = 'controller'

When matched, it will be available via match.node.label:

var match = router.match('/someid/somecontroller')
assert(match.node.label === 'label')

Since reaching into match.node is a little inconvenient and you probably don't want your end users to touch it, you should expose in your dispatcher:

var match = router.match(url.parse(req.url).pathname)

// ...

req.param = match.param
req.label = match.node.label

Browser Support

IE9+

More Repositories

1

path-to-regexp

Turn a path string such as `/user/:name` into a regular expression
TypeScript
8,041
star
2

hbs

Express view engine wrapper for Handlebars
JavaScript
1,659
star
3

understanding-csrf

What are CSRF tokens and how do they work?
1,391
star
4

multiparty

A node.js module for parsing multipart-form data requests which supports streams2
JavaScript
1,298
star
5

cookies

Signed and unsigned cookies based on Keygrip
JavaScript
1,283
star
6

send

Streaming static file server with Range and conditional-GET support
JavaScript
791
star
7

router

Simple middleware-style router
JavaScript
404
star
8

node-frameworks

A comparison of server-side node frameworks
313
star
9

csrf

Logic behind CSRF token creation and verification.
JavaScript
294
star
10

finalhandler

Node.js final http responder
JavaScript
215
star
11

parseurl

parse a url with memoization
JavaScript
188
star
12

path-match

please use path-to-regexp's `match` function
JavaScript
138
star
13

encodeurl

Encode a URL to a percent-encoded form, excluding already-encoded sequences
JavaScript
34
star
14

resolve-path

Resolve a relative path against a root path with validation
JavaScript
32
star
15

templation

[ON HOLD] an asynchronous, extensible view system
JavaScript
13
star
16

ssl-redirect

redirect users to the SSL version of your app
JavaScript
11
star
17

discussions

http://pillarjs.github.io
7
star
18

qs-strict

[ON HOLD] pillarjs
JavaScript
4
star
19

extend-proto

generic __proto__ injection utility
JavaScript
3
star
20

re2js-legendary

a node v0.10 compatible build of RE2JS
JavaScript
3
star
21

request

Express style request object
JavaScript
2
star
22

.github

2
star
23

views

Node.js view rendering abstraction.
1
star