-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRouter.js
66 lines (58 loc) · 1.62 KB
/
Router.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
const Rule = require('./Rule');
const Route = require('./Route');
const p = require('path');
const rulesKey = Symbol('#rules');
const areasKey = Symbol('#areas');
const getMatchedResultKey = Symbol('#getMatchedResultKey');
module.exports = class Router{
get rules(){
return this[rulesKey];
}
get areas(){
return this[areasKey];
}
constructor({
rules = [],
areas = []
} = {}){
if(!Array.isArray(rules)){
rules = [rules];
}
if(rules.length===0){
rules.push('{{controller:home}}/{{action:index}}')
}
this[areasKey] = areas;
this[rulesKey] = [];
for(let rule of rules){
this[rulesKey].push(new Rule(rule));
}
}
[getMatchedResultKey](path){
for(let rule of this.rules){
const result = rule.match(path);
if(result) return result;
}
return null;
}
match(path){
if(path.startsWith('/')) path = path.substr(1);
let area = '';
let areaPath = '';
for(let areaName of this.areas){
if(path.startsWith(areaName)){
area = areaName;
areaPath = p.relative(areaName, path);
}
}
if(area){
const params = this[getMatchedResultKey](areaPath);
if(params) return new Route(params, area);
}
const params = this[getMatchedResultKey](path);
if(params) return new Route(params);
return null;
}
resolve(params, area){
return p.join('/'+area, this.rules[0].resolve(params));
}
}