-
Notifications
You must be signed in to change notification settings - Fork 0
/
route.js
202 lines (174 loc) · 5.92 KB
/
route.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/**
* Created by yss on 9/5/16.
*/
'use strict';
const FS = require('fs');
const Path = require('path');
function isDirectory(filepath) {
if (FS.existsSync(filepath)) {
return FS.statSync(filepath).isDirectory();
}
}
function initController(controller, dirname) {
FS.readdirSync(dirname).forEach(function(item) {
const filepath = Path.join(dirname, item);
if (isDirectory(filepath)) {
if (!controller[item]) {
controller[item] = {};
}
initController(controller[item], filepath);
} else if (/\.js$/.test(item) && item.indexOf('.') !== 0) { // js file and not hidden file
const pathname = item.slice(0, -3);
controller[pathname] = Object.assign(controller[pathname] || {}, require(filepath));
}
});
}
function addAlias(alias, controller) {
if (!alias || typeof alias !== TYPE_OBJECT) {
return;
}
Object.keys(alias).forEach(function(key) {
let fn = controller;
alias[key].split('/').forEach(function(method) {
if (method) {
fn = fn[method];
}
});
if (typeof fn !== TYPE_FUNCTION && typeof fn !== TYPE_OBJECT) {
throw new Error('Alias value must be a function or object.');
}
let aliasController = controller;
const keyArr = key.split('/');
key = keyArr.pop();
keyArr.forEach(function(method) {
if (method) {
aliasController = aliasController[method] = aliasController[method] || {};
}
});
if (aliasController.hasOwnProperty(key)) {
throw new Error('The key `' + key + '` is exists, and can not be replaced.\nPlease remove it and try again.');
}
aliasController[key] = fn;
});
}
const METHODS = 'post,put,patch,delete'.split(','); // specially for get and head
const TYPE_FUNCTION = 'function';
const TYPE_OBJECT = 'object';
const METHOD_GET = 'GET';
const METHOD_HEAD = 'HEAD';
const METHOD_OPTIONS = 'OPTIONS';
const PATH_DEFAULT = 'index';
function getActionName (app, reqMethod, path, pathArr) {
let actionName = METHOD_GET === reqMethod ? path : reqMethod.toLowerCase() + path.substring(0, 1).toUpperCase() + path.substring(1);
if (typeof app[actionName] !== TYPE_FUNCTION) {
if (!Array.isArray(pathArr) || pathArr.length === 0) {
return;
}
if ((actionName = getActionName(app, reqMethod, pathArr[0]))) {
pathArr.splice(0, 1, path);
}
}
return actionName;
}
/**
* koa-route-tree
* @param {String} dirname
* @param {Object} [alias]
* @param {Function} [withoutRouteHandler]
* @return {Function}
*/
function Route(dirname, alias, withoutRouteHandler) {
const controller = {};
if (typeof alias === TYPE_FUNCTION) {
withoutRouteHandler = alias;
alias = null;
}
initController(controller, dirname);
addAlias(alias, controller);
// prevent the controller object to be modified.
Object.freeze(controller);
async function router(ctx, next) {
const pathArr = ctx.path.substring(1).split('/');
const reqMethod = ctx.method;
let app = controller,
path,
method;
if (pathArr[0] && !app[pathArr[0]]) {
if (typeof withoutRouteHandler === TYPE_FUNCTION) {
return await withoutRouteHandler(ctx, next, controller);
}
return ctx.throw(404, 'ROUTE_NOT_FOUND');
}
while (true) { /*eslint no-constant-condition:0*/
path = pathArr.shift() || PATH_DEFAULT;
if (typeof app[path] === TYPE_OBJECT) {
app = app[path];
continue;
}
if (reqMethod === METHOD_HEAD) {
Route.headRequestHandler(ctx, app, path, pathArr[0]);
break;
}
if (reqMethod === METHOD_OPTIONS) {
Route.optionsRequestHandler(ctx, app, path, pathArr[0]);
break;
}
if ((method = getActionName(app, reqMethod, path, pathArr))) {
await app[method].apply(ctx, pathArr);
} else if (
PATH_DEFAULT !== path &&
(method = getActionName(app, reqMethod, PATH_DEFAULT))
) {
pathArr.unshift(path);
await app[method].apply(ctx, pathArr);
} else {
ctx.throw(404, 'ROUTE_NOT_FOUND');
}
break;
}
}
router.controller = controller;
return router;
}
/**
* for OPTIONS /
* @param ctx
* @param {Object} app the last controller object
* @param {String} path
* @param {String} pathExtra
*/
Route.optionsRequestHandler = function(ctx, app, path, pathExtra) {
const methods = [];
if (typeof app[path] === TYPE_FUNCTION || typeof app[pathExtra] === TYPE_FUNCTION || typeof app.index === TYPE_FUNCTION) {
methods.push(METHOD_HEAD, METHOD_GET);
}
METHODS.forEach(function(method) {
[path, pathExtra].some(function (path) {
if (path
&& (typeof app[method + path.substring(0, 1).toUpperCase() + path.substring(1)] === TYPE_FUNCTION
|| typeof app[method + 'Index'] === TYPE_FUNCTION)) {
methods.push(method.toUpperCase());
return true;
}
});
});
ctx.set('Allow', methods.join(','));
ctx.body = methods.join(',');
};
/**
* for HEAD /
* @param ctx
* @param {Object} app the last controller object
* @param {String} path
* @param {String} pathExtra
*/
Route.headRequestHandler = function(ctx, app, path, pathExtra) {
if (typeof app[path] === TYPE_FUNCTION
|| (pathExtra && typeof app[pathExtra] === TYPE_FUNCTION)
|| typeof app.index === TYPE_FUNCTION) {
ctx.status = 200;
} else {
ctx.status = 404;
}
};
module.exports = Route;