-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
82 lines (69 loc) · 2.37 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
'use strict';
// Module dependencies
const glob = require('glob');
const os = require('os');
const compose = require('./lib/compose');
const METHOD_ENUM = ['get', 'post', 'put', 'delete', 'patch'];
function loadRouter(app, root, options) {
const opt = options || {};
glob.sync(`${root}/**/*.js`).forEach((file) => {
const realRoot = os.platform() === 'win32' ? root.replace(/\\/ig, '/') : root;
const filePath = file.replace(/\.[^.]*$/, '');
const controller = require(filePath);
const urlPrefix = filePath.replace(realRoot, '').replace(/\/index$/, '');
const methods = Object.keys(controller);
// Handle options
const excludeRules = opt.excludeRules || [];
const rewriteRules = opt.rewriteRules || new Map();
function applyMethod(name, methodBody) {
const body = methodBody;
let modifiedUrl = `${urlPrefix}${name === 'index' ? '' : `/${name}`}`;
let middlewares = [];
let method = 'get';
let handler;
let params;
switch (typeof body) {
case 'object':
params = body.params || [];
middlewares = body.middlewares || [];
modifiedUrl += `/${params.join('/')}`;
handler = body.handler;
method = (body.method || 'get').toLowerCase();
break;
case 'function':
handler = body;
break;
default: return;
}
function applyUrl(url) {
app[method](rewriteRules.has(url) ?
rewriteRules.get(url) :
url, compose(middlewares, url), handler);
}
if (excludeRules.indexOf(modifiedUrl) !== -1) {
// Nothing to-do with the excluded rules
} else if (METHOD_ENUM.indexOf(method) !== -1) {
if (!handler) throw Error('[express-load-router]: no handler for method: ', method);
// 这里兼容两种 index 的访问方式
applyUrl(modifiedUrl);
if (name === 'index') {
applyUrl(`${modifiedUrl}/index`);
}
} else {
throw Error('[load-router]: invalid method: ', method);
}
}
methods.forEach((method) => {
const methodName = method;
const methodBody = controller[method];
if (Array.isArray(methodBody)) {
methodBody.forEach((m) => {
applyMethod(methodName, m);
});
} else {
applyMethod(methodName, methodBody);
}
});
});
}
module.exports = loadRouter;