choo-shortcache
Version:
choo nanocomponent cache shortcut
78 lines (59 loc) • 1.69 kB
JavaScript
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, fn) {
assert.equal(typeof route, 'string')
assert.equal(typeof fn, 'function')
var cb = fn._wayfarer && fn._trie ? fn : proxy
route = route || '/'
cb.route = route
if (cb._wayfarer && cb._trie) {
_trie.mount(route, cb._trie.trie)
} else {
var node = _trie.create(route)
node.cb = cb
}
return emit
function proxy () {
return fn.apply(this, Array.prototype.slice.call(arguments))
}
}
// 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.cb.route
this.params = matched.params
}
}