-
Notifications
You must be signed in to change notification settings - Fork 176
/
layer.js
240 lines (213 loc) · 6.32 KB
/
layer.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
const { parse: parseUrl, format: formatUrl } = require('node:url');
const { pathToRegexp, compile, parse } = require('path-to-regexp');
module.exports = class Layer {
/**
* Initialize a new routing Layer with given `method`, `path`, and `middleware`.
*
* @param {String|RegExp} path Path string or regular expression.
* @param {Array} methods Array of HTTP verbs.
* @param {Array} middleware Layer callback/middleware or series of.
* @param {Object=} opts
* @param {String=} opts.name route name
* @param {String=} opts.sensitive case sensitive (default: false)
* @param {String=} opts.strict require the trailing slash (default: false)
* @returns {Layer}
* @private
*/
constructor(path, methods, middleware, opts = {}) {
this.opts = opts;
this.name = this.opts.name || null;
this.methods = [];
this.paramNames = [];
this.stack = Array.isArray(middleware) ? middleware : [middleware];
for (const method of methods) {
const l = this.methods.push(method.toUpperCase());
if (this.methods[l - 1] === 'GET') this.methods.unshift('HEAD');
}
// ensure middleware is a function
for (let i = 0; i < this.stack.length; i++) {
const fn = this.stack[i];
const type = typeof fn;
if (type !== 'function')
throw new Error(
`${methods.toString()} \`${
this.opts.name || path
}\`: \`middleware\` must be a function, not \`${type}\``
);
}
this.path = path;
this.regexp = pathToRegexp(path, this.paramNames, this.opts);
}
/**
* Returns whether request `path` matches route.
*
* @param {String} path
* @returns {Boolean}
* @private
*/
match(path) {
return this.regexp.test(path);
}
/**
* Returns map of URL parameters for given `path` and `paramNames`.
*
* @param {String} path
* @param {Array.<String>} captures
* @param {Object=} params
* @returns {Object}
* @private
*/
params(path, captures, params = {}) {
for (let len = captures.length, i = 0; i < len; i++) {
if (this.paramNames[i]) {
const c = captures[i];
if (c && c.length > 0)
params[this.paramNames[i].name] = c ? safeDecodeURIComponent(c) : c;
}
}
return params;
}
/**
* Returns array of regexp url path captures.
*
* @param {String} path
* @returns {Array.<String>}
* @private
*/
captures(path) {
return this.opts.ignoreCaptures ? [] : path.match(this.regexp).slice(1);
}
/**
* Generate URL for route using given `params`.
*
* @example
*
* ```javascript
* const route = new Layer('/users/:id', ['GET'], fn);
*
* route.url({ id: 123 }); // => "/users/123"
* ```
*
* @param {Object} params url parameters
* @returns {String}
* @private
*/
url(params, options) {
let args = params;
const url = this.path.replace(/\(\.\*\)/g, '');
if (typeof params !== 'object') {
args = Array.prototype.slice.call(arguments);
if (typeof args[args.length - 1] === 'object') {
options = args[args.length - 1];
args = args.slice(0, -1);
}
}
const toPath = compile(url, { encode: encodeURIComponent, ...options });
let replaced;
const tokens = parse(url);
let replace = {};
if (Array.isArray(args)) {
for (let len = tokens.length, i = 0, j = 0; i < len; i++) {
if (tokens[i].name) replace[tokens[i].name] = args[j++];
}
} else if (tokens.some((token) => token.name)) {
replace = params;
} else if (!options) {
options = params;
}
replaced = toPath(replace);
if (options && options.query) {
replaced = parseUrl(replaced);
if (typeof options.query === 'string') {
replaced.search = options.query;
} else {
replaced.search = undefined;
replaced.query = options.query;
}
return formatUrl(replaced);
}
return replaced;
}
/**
* Run validations on route named parameters.
*
* @example
*
* ```javascript
* router
* .param('user', function (id, ctx, next) {
* ctx.user = users[id];
* if (!ctx.user) return ctx.status = 404;
* next();
* })
* .get('/users/:user', function (ctx, next) {
* ctx.body = ctx.user;
* });
* ```
*
* @param {String} param
* @param {Function} middleware
* @returns {Layer}
* @private
*/
param(param, fn) {
const { stack } = this;
const params = this.paramNames;
const middleware = function (ctx, next) {
return fn.call(this, ctx.params[param], ctx, next);
};
middleware.param = param;
const names = params.map(function (p) {
return p.name;
});
const x = names.indexOf(param);
if (x > -1) {
// iterate through the stack, to figure out where to place the handler fn
stack.some((fn, i) => {
// param handlers are always first, so when we find an fn w/o a param property, stop here
// if the param handler at this part of the stack comes after the one we are adding, stop here
if (!fn.param || names.indexOf(fn.param) > x) {
// inject this param handler right before the current item
stack.splice(i, 0, middleware);
return true; // then break the loop
}
});
}
return this;
}
/**
* Prefix route path.
*
* @param {String} prefix
* @returns {Layer}
* @private
*/
setPrefix(prefix) {
if (this.path) {
this.path =
this.path !== '/' || this.opts.strict === true
? `${prefix}${this.path}`
: prefix;
this.paramNames = [];
this.regexp = pathToRegexp(this.path, this.paramNames, this.opts);
}
return this;
}
};
/**
* Safe decodeURIComponent, won't throw any error.
* If `decodeURIComponent` error happen, just return the original value.
*
* @param {String} text
* @returns {String} URL decode original string.
* @private
*/
function safeDecodeURIComponent(text) {
try {
// TODO: take a look on `safeDecodeURIComponent` if we use it only with route params let's remove the `replace` method otherwise make it flexible.
// @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent#decoding_query_parameters_from_a_url
return decodeURIComponent(text.replace(/\+/g, ' '));
} catch {
return text;
}
}