-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
80 lines (72 loc) · 1.54 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
74
75
76
77
78
79
80
/**
* Dependencies.
*/
const regexp = require('path-to-regexp')
/**
* Create path router.
*
* @param {Object} obj
* @return {Function}
* @api public
*/
module.exports = function (obj, prefix = '') {
const staticRoutes = {}
const dynamicRoutes = []
Object
.keys(obj)
.map(path => {
const keys = []
const url = path
path = prefix + path
const match = regexp(path, keys)
if (!keys.length) {
staticRoutes[normalize(path)] = obj[path]
} else {
dynamicRoutes.push({
re: match,
fn: obj[url],
keys: keys
})
}
})
return (url) => {
let handler = staticRoutes[normalize(url)]
if (handler) {
return {
arg: handler
}
} else {
for (var i = 0, l = dynamicRoutes.length; i < l; i++) {
const layer = dynamicRoutes[i]
const match = layer.re.exec(url)
if (match) {
const params = {}
layer.keys.map((key, idx) => {
let param = match[idx + 1]
if (param) {
param = decodeURIComponent(param)
if (key.repeat) param = param.split(key.delimiter)
params[key.name] = param
}
})
return {
arg: layer.fn,
params: params
}
break
}
}
}
}
}
/**
* Normalize path name.
*
* @param {String} pathname
* @return {String}
* @api private
*/
function normalize (pathname) {
let suffix = pathname.substr(-1) !== '/' ? '/' : ''
return pathname + suffix
}