1 | const assert = require('assert')
|
2 | const trie = require('./trie')
|
3 |
|
4 | module.exports = Wayfarer
|
5 |
|
6 |
|
7 |
|
8 | function Wayfarer (dft) {
|
9 | if (!(this instanceof Wayfarer)) return new Wayfarer(dft)
|
10 |
|
11 | const _default = (dft || '').replace(/^\//, '')
|
12 | const _trie = trie()
|
13 |
|
14 | emit._trie = _trie
|
15 | emit.emit = emit
|
16 | emit.on = on
|
17 | emit._wayfarer = true
|
18 |
|
19 | return emit
|
20 |
|
21 |
|
22 |
|
23 | function on (route, cb) {
|
24 | assert.equal(typeof route, 'string')
|
25 | assert.equal(typeof cb, 'function')
|
26 |
|
27 | route = route || '/'
|
28 |
|
29 | if (cb && cb._wayfarer && cb._trie) {
|
30 | _trie.mount(route, cb._trie.trie)
|
31 | } else {
|
32 | const node = _trie.create(route)
|
33 | node.cb = cb
|
34 | }
|
35 |
|
36 | return emit
|
37 | }
|
38 |
|
39 |
|
40 |
|
41 | function emit (route) {
|
42 | assert.notEqual(route, undefined, "'route' must be defined")
|
43 | const args = Array.prototype.slice.apply(arguments)
|
44 |
|
45 | const node = _trie.match(route)
|
46 | if (node && node.cb) {
|
47 | args[0] = node.params
|
48 | return node.cb.apply(null, args)
|
49 | }
|
50 |
|
51 | const dft = _trie.match(_default)
|
52 | if (dft && dft.cb) {
|
53 | args[0] = dft.params
|
54 | return dft.cb.apply(null, args)
|
55 | }
|
56 |
|
57 | throw new Error("route '" + route + "' did not match")
|
58 | }
|
59 | }
|