-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
109 lines (99 loc) · 2.66 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
const Router = require('./router.js');
const helper = require('think-helper');
const pathToRegexp = require('path-to-regexp');
/**
* default options
*/
const defaultOptions = {
defaultModule: 'home', // default module name, is enable in multi module mode
defaultController: 'index', // default controller name
defaultAction: 'index', // default action name
prefix: [], // url prefix
suffix: ['.html'], // url suffix
enableDefaultRouter: true,
optimizeHomepageRouter: true,
subdomainOffset: 2,
subdomain: {}, // subdomain
denyModules: [] // deny module, enable in multi module mode
};
/**
* format Rule
* @param {Array} rule
*/
const formatRule = rule => {
const query = [];
const match = pathToRegexp(rule[0], query);
// [/match/, 'rest'] for simple restful router
if (rule.length === 2 && rule[1].toUpperCase() === 'REST') {
rule[2] = rule[1];
rule[1] = null;
}
return {
match,
path: rule[1],
method: rule[2] && rule[2].toUpperCase(),
options: rule[3] || {},
query
};
};
/**
* format routers
* @param {Array|Object} routers
*/
const formatRouters = routers => {
if (helper.isArray(routers)) {
return routers.map(item => {
if (item.isFormatted) return item;
if (item.rules) {
item.match = pathToRegexp(item.match);
item.rules = item.rules.map(rule => {
return formatRule(rule);
});
} else {
item = formatRule(item);
}
item.isFormatted = 1;
return item;
});
}
for (const m in routers) {
if (routers[m].isFormatted) continue;
if (routers[m].match) {
routers[m].match = pathToRegexp(routers[m].match);
}
routers[m].rules = formatRouters(routers[m].rules);
routers[m].isFormatted = 1;
}
return routers;
};
/**
* parse router
*/
module.exports = function parseRouter(options, app) {
options = Object.assign(defaultOptions, options);
// set subdomain offset
if (options.subdomainOffset) {
app.subdomainOffset = options.subdomainOffset;
}
// change subdomain array to object
// subdomain: ['admin', 'user'] => {admin: 'admin', user: 'ussr'}
if (helper.isArray(options.subdomain)) {
const subdomain = {};
options.subdomain.forEach(item => {
subdomain[item] = item;
});
options.subdomain = subdomain;
}
// format routers when routerChange event fired
app.on('routerChange', routers => {
app.routers = formatRouters(routers);
});
// format routers when app ready
app.once('appReady', () => {
app.routers = formatRouters(app.routers);
});
return function router(ctx, next) {
const instance = new Router(ctx, next, options);
return instance.run();
};
};