-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
39 lines (31 loc) · 961 Bytes
/
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
import { match } from 'path-to-regexp';
function routemeup (routes, { method, url }) {
const parsedUrl = new URL(url, 'http://example.com');
const pathname = parsedUrl.pathname + parsedUrl.hash;
for (const route in routes) {
const matched = match(route, { decode: decodeURIComponent })(pathname);
if (matched) {
const controller = routes[route];
if (typeof controller === 'function') {
return {
controller: controller,
tokens: matched.params
};
}
if (method) {
const requestMethod = method.toUpperCase();
const controllerMethod = Object
.keys(controller)
.find(key => key.toUpperCase() === requestMethod);
if (!controller[controllerMethod]) {
return null;
}
return {
controller: controller[controllerMethod],
tokens: matched.params
};
}
}
}
}
export default routemeup;