@eggjs/router 2.0.1 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/Layer.ts ADDED
@@ -0,0 +1,274 @@
1
+ import { debuglog } from 'node:util';
2
+ import pathToRegExp, { type Key } from 'path-to-regexp';
3
+ import URI from 'urijs';
4
+ import { decodeURIComponent as safeDecodeURIComponent } from 'utility';
5
+ import { isGeneratorFunction } from 'is-type-of';
6
+ import type {
7
+ MiddlewareFunc,
8
+ MiddlewareFuncWithParamProperty,
9
+ ParamMiddlewareFunc,
10
+ } from './types.js';
11
+
12
+ const debug = debuglog('egg-router:layer');
13
+
14
+ export interface LayerOptions {
15
+ prefix?: string;
16
+ /** route name */
17
+ name?: string;
18
+ /** case sensitive (default: false) */
19
+ sensitive?: boolean;
20
+ /** require the trailing slash (default: false) */
21
+ strict?: boolean;
22
+ ignoreCaptures?: boolean;
23
+ end?: boolean;
24
+ }
25
+
26
+ export interface LayerURLOptions {
27
+ query?: string | object;
28
+ }
29
+
30
+ export class Layer {
31
+ readonly opts: LayerOptions;
32
+ readonly name?: string;
33
+ readonly methods: string[] = [];
34
+ readonly stack: MiddlewareFuncWithParamProperty[];
35
+ path: string | RegExp;
36
+ regexp: RegExp;
37
+ paramNames: Key[] = [];
38
+
39
+ /**
40
+ * Initialize a new routing Layer with given `method`, `path`, and `middleware`.
41
+ *
42
+ * @param {String|RegExp} path Path string or regular expression.
43
+ * @param {Array} methods Array of HTTP verbs.
44
+ * @param {Array|Function} middlewares Layer callback/middleware or series of.
45
+ * @param {Object=} opts optional params
46
+ * @param {String=} opts.name route name
47
+ * @param {String=} opts.sensitive case sensitive (default: false)
48
+ * @param {String=} opts.strict require the trailing slash (default: false)
49
+ * @private
50
+ */
51
+ constructor(path: string | RegExp, methods: string[], middlewares: MiddlewareFunc | MiddlewareFunc[],
52
+ opts?: LayerOptions | string) {
53
+ if (typeof opts === 'string') {
54
+ // new Layer(path, methods, middlewares, name);
55
+ opts = { name: opts };
56
+ }
57
+ this.opts = opts ?? {};
58
+ this.opts.prefix = this.opts.prefix ?? '';
59
+ this.name = this.opts.name;
60
+ this.stack = Array.isArray(middlewares) ? middlewares : [ middlewares ];
61
+
62
+ for (const method of methods) {
63
+ const l = this.methods.push(method.toUpperCase());
64
+ if (this.methods[l - 1] === 'GET') {
65
+ this.methods.unshift('HEAD');
66
+ }
67
+ }
68
+
69
+ // ensure middleware is a function
70
+ this.stack.forEach(fn => {
71
+ const type = typeof fn;
72
+ if (type !== 'function') {
73
+ throw new TypeError(
74
+ methods.toString() + ' `' + (this.opts.name || path) + '`: `middleware` '
75
+ + 'must be a function, not `' + type + '`',
76
+ );
77
+ }
78
+ if (isGeneratorFunction(fn)) {
79
+ throw new TypeError(
80
+ methods.toString() + ' `' + (this.opts.name || path) + '`: Please use async function instead of generator function',
81
+ );
82
+ }
83
+ });
84
+
85
+ this.path = path;
86
+ this.regexp = pathToRegExp(path, this.paramNames, this.opts);
87
+
88
+ debug('defined route %s %s', this.methods, this.opts.prefix + this.path);
89
+ }
90
+
91
+ /**
92
+ * Returns whether request `path` matches route.
93
+ *
94
+ * @param {String} path path string
95
+ * @return {Boolean} matched or not
96
+ * @private
97
+ */
98
+ match(path: string): boolean {
99
+ return this.regexp.test(path);
100
+ }
101
+
102
+ /**
103
+ * Returns map of URL parameters for given `path` and `paramNames`.
104
+ *
105
+ * @param {String} _path path string
106
+ * @param {Array.<String>} captures captures strings
107
+ * @param {Object=} [existingParams] existing params
108
+ * @return {Object} params object
109
+ * @private
110
+ */
111
+ params(_path: string, captures: Array<string>, existingParams?: Record<string, string>): Record<string, string> {
112
+ const params = existingParams ?? {};
113
+
114
+ for (let len = captures.length, i = 0; i < len; i++) {
115
+ const paramName = this.paramNames[i];
116
+ if (paramName) {
117
+ const c = captures[i];
118
+ params[paramName.name] = c ? safeDecodeURIComponent(c) : c;
119
+ }
120
+ }
121
+ return params;
122
+ }
123
+
124
+ /**
125
+ * Returns array of regexp url path captures.
126
+ *
127
+ * @param {String} path path string
128
+ * @return {Array.<String>} captures strings
129
+ * @private
130
+ */
131
+ captures(path: string): Array<string> {
132
+ if (this.opts.ignoreCaptures) return [];
133
+ const m = path.match(this.regexp);
134
+ return m ? m.slice(1) : [];
135
+ }
136
+
137
+ /**
138
+ * Generate URL for route using given `params`.
139
+ *
140
+ * @example
141
+ *
142
+ * ```javascript
143
+ * var route = new Layer(['GET'], '/users/:id', fn);
144
+ *
145
+ * route.url(123); // => "/users/123"
146
+ * route.url('123'); // => "/users/123"
147
+ * route.url({ id: 123 }); // => "/users/123"
148
+ * ```
149
+ *
150
+ * @param {Object} params url parameters
151
+ * @param {Object} paramsOrOptions optional parameters
152
+ * @return {String} url string
153
+ * @private
154
+ */
155
+ url(params?: string | number | object, ...paramsOrOptions: (string | number | object | LayerURLOptions)[]): string {
156
+ let args: Array<string | number | object> | object = params as object;
157
+ const url = (this.path as string).replace(/\(\.\*\)/g, '');
158
+ const toPath = pathToRegExp.compile(url);
159
+ let options: LayerURLOptions | undefined;
160
+
161
+ if (params !== undefined && typeof params !== 'object') {
162
+ args = [ params, ...paramsOrOptions ];
163
+ // route.url(stringOrNumber, params1, ..., options);
164
+ if (Array.isArray(args)) {
165
+ const lastIndex = args.length - 1;
166
+ if (typeof args[lastIndex] === 'object') {
167
+ options = args[lastIndex];
168
+ args = args.slice(0, lastIndex);
169
+ }
170
+ }
171
+ } else if (typeof params === 'object') {
172
+ if (typeof paramsOrOptions[0] === 'object' && 'query' in paramsOrOptions[0]) {
173
+ // route.url(param, options);
174
+ options = paramsOrOptions[0];
175
+ }
176
+ }
177
+
178
+ const tokens = pathToRegExp.parse(url);
179
+ let replace: Record<string, any> = {};
180
+
181
+ if (Array.isArray(args)) {
182
+ for (let len = tokens.length, i = 0, j = 0; i < len; i++) {
183
+ const token = tokens[i];
184
+ if (typeof token === 'object' && token.name) {
185
+ replace[token.name] = args[j++];
186
+ }
187
+ }
188
+ } else if (tokens.some(token => typeof token === 'object' && token.name)) {
189
+ // route.url(params);
190
+ replace = params as object;
191
+ } else {
192
+ // route.url(options);
193
+ options = params as LayerURLOptions;
194
+ }
195
+
196
+ const replaced = toPath(replace);
197
+
198
+ if (options?.query) {
199
+ const urlObject = new URI(replaced);
200
+ urlObject.search(options.query);
201
+ return urlObject.toString();
202
+ }
203
+
204
+ return replaced;
205
+ }
206
+
207
+ /**
208
+ * Run validations on route named parameters.
209
+ *
210
+ * @example
211
+ *
212
+ * ```javascript
213
+ * router
214
+ * .param('user', function (id, ctx, next) {
215
+ * ctx.user = users[id];
216
+ * if (!user) return ctx.status = 404;
217
+ * next();
218
+ * })
219
+ * .get('/users/:user', function (ctx, next) {
220
+ * ctx.body = ctx.user;
221
+ * });
222
+ * ```
223
+ *
224
+ * @param {String} param param string
225
+ * @param {Function} fn middleware function
226
+ * @return {Layer} layer instance
227
+ * @private
228
+ */
229
+ param(param: string, fn: ParamMiddlewareFunc): Layer {
230
+ const stack = this.stack;
231
+ const params = this.paramNames;
232
+ const middleware: MiddlewareFuncWithParamProperty = function(this: any, ctx, next) {
233
+ return fn.call(this, ctx.params[param], ctx, next);
234
+ };
235
+ middleware.param = param;
236
+
237
+ const names = params.map(p => {
238
+ return p.name;
239
+ });
240
+
241
+ const x = names.indexOf(param);
242
+ if (x > -1) {
243
+ // iterate through the stack, to figure out where to place the handler fn
244
+ stack.some(function(fn, i) {
245
+ // param handlers are always first, so when we find an fn w/o a param property, stop here
246
+ // if the param handler at this part of the stack comes after the one we are adding, stop here
247
+ if (!fn.param || names.indexOf(fn.param) > x) {
248
+ // inject this param handler right before the current item
249
+ stack.splice(i, 0, middleware);
250
+ return true; // then break the loop
251
+ }
252
+ return false;
253
+ });
254
+ }
255
+
256
+ return this;
257
+ }
258
+
259
+ /**
260
+ * Prefix route path.
261
+ *
262
+ * @param {String} prefix prefix string
263
+ * @return {Layer} layer instance
264
+ * @private
265
+ */
266
+ setPrefix(prefix: string): Layer {
267
+ if (this.path) {
268
+ this.path = prefix + this.path;
269
+ this.paramNames = [];
270
+ this.regexp = pathToRegExp(this.path, this.paramNames, this.opts);
271
+ }
272
+ return this;
273
+ }
274
+ }