-
Notifications
You must be signed in to change notification settings - Fork 31
/
index.js
73 lines (56 loc) · 1.55 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* eslint-disable node/no-deprecated-api */
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
}
}