-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathrouter.js
More file actions
50 lines (49 loc) · 1.41 KB
/
router.js
File metadata and controls
50 lines (49 loc) · 1.41 KB
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
function getQueryStringParams(query) {
if(query) {
query = (/^[?#]/.test(query) ? query.slice(1) : query);
return query.split('&').reduce((params, param) => {
let [key, value] = param.split('=');
params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
if(params[key] === 'true') {
params[key] = true;
} else if (params[key] === 'false') {
params[key] = false;
} else if(/^\d+$/.test(params[key])) {
params[key] = parseInt(params[key]);
}
return params;
}, {});
} else {
return {};
}
};
export function getPageWithParamsFromPath(routes, url) {
let page;
let [path, query] = url.split('?');
let params = getQueryStringParams(query);
const intentions = path.split('/');
for(let route of routes) {
const matchers = route.path.split('/');
if(intentions.length == matchers.length) {
const matches = matchers.map(function(matcher, index) {
if(matcher.startsWith(':')) {
params[matcher.replace(':', '')] = intentions[index];
return true;
} else {
return matcher == intentions[index];
}
}).every((matches) => matches);
if(matches) {
page = route.page;
break;
}
}
if(!page) {
let route = routes.find((route) => route.path == '*');
if(route) {
page = route.page;
}
}
}
return {page, params};
}