This repository has been archived by the owner on Sep 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
55 lines (52 loc) · 1.49 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
const Routes = {}
const weight = (route) => -100*route.split('/').length +
route.split('/').reduce((len, item) => len + item.length, 0) +
10000 * (route.indexOf('*') != -1 ? 1 : 0)
export default (url, action) => {
if (action === undefined) {
return Object.keys(Routes)
.sort((a, b) => Routes[a].weight - Routes[b].weight)
.reduce((match, route) => {
if (!match) {
const Route = route.split('/')
var Url = url.split('?')
const Path = Url.shift().split('/')
const Response = {
route: route,
url: url,
path: Path.join('/'),
params: {},
query: Url.join('?')
}
status = 'okay'
Route.forEach((r, i) => {
if (status) {
if (Path[i] == null) {
status = ''
} else if (r === '*') {
status = '*'
} else if (r.substr(0, 1) === ':') {
Response.params[r.substr(1)] = Path[i]
} else if (r !== Path[i]) {
status = ''
}
}
})
if (status == '*' || (status && Route.length == Path.length)) {
Routes[route].action(Response)
match = true
}
}
return match
}, false)
} else {
if (typeof action !== 'function') {
delete Routes[url]
} else {
Routes[url] = {
action: action,
weight: weight(url)
}
}
}
}