Permalink
Join GitHub today
GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.
Sign up
Fetching contributors…
Cannot retrieve contributors at this time.
Cannot retrieve contributors at this time
| var assert = require('assert') | |
| var trie = require('./trie') | |
| module.exports = Wayfarer | |
| // create a router | |
| // str -> obj | |
| function Wayfarer (dft) { | |
| if (!(this instanceof Wayfarer)) return new Wayfarer(dft) | |
| var _default = (dft || '').replace(/^\//, '') | |
| var _trie = trie() | |
| emit._trie = _trie | |
| emit.on = on | |
| emit.emit = emit | |
| emit.match = match | |
| emit._wayfarer = true | |
| return emit | |
| // define a route | |
| // (str, fn) -> obj | |
| function on (route, cb) { | |
| assert.equal(typeof route, 'string') | |
| assert.equal(typeof cb, 'function') | |
| route = route || '/' | |
| if (cb._wayfarer && cb._trie) { | |
| _trie.mount(route, cb._trie.trie) | |
| } else { | |
| var node = _trie.create(route) | |
| node.cb = cb | |
| node.route = route | |
| } | |
| return emit | |
| } | |
| // match and call a route | |
| // (str, obj?) -> null | |
| function emit (route) { | |
| var matched = match(route) | |
| var args = new Array(arguments.length) | |
| args[0] = matched.params | |
| for (var i = 1; i < args.length; i++) { | |
| args[i] = arguments[i] | |
| } | |
| return matched.cb.apply(matched.cb, args) | |
| } | |
| function match (route) { | |
| assert.notEqual(route, undefined, "'route' must be defined") | |
| var matched = _trie.match(route) | |
| if (matched && matched.cb) return new Route(matched) | |
| var dft = _trie.match(_default) | |
| if (dft && dft.cb) return new Route(dft) | |
| throw new Error("route '" + route + "' did not match") | |
| } | |
| function Route (matched) { | |
| this.cb = matched.cb | |
| this.route = matched.route | |
| this.params = matched.params | |
| } | |
| } |