@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/README.md CHANGED
@@ -1,55 +1,68 @@
1
1
  # @eggjs/router
2
2
 
3
+ [![NPM version](https://img.shields.io/npm/v/@eggjs/router.svg?style=flat-square)](https://npmjs.org/package/@eggjs/router)
4
+ [![NPM download](https://img.shields.io/npm/dm/@eggjs/router.svg?style=flat-square)](https://npmjs.org/package/@eggjs/router)
5
+ [![Node.js CI](https://github.com/eggjs/egg-router/actions/workflows/nodejs.yml/badge.svg?branch=master)](https://github.com/eggjs/egg-router/actions/workflows/nodejs.yml)
6
+ [![Test coverage](https://img.shields.io/codecov/c/github/eggjs/egg-router.svg?style=flat-square)](https://codecov.io/gh/eggjs/egg-router)
7
+ [![Known Vulnerabilities](https://snyk.io/test/npm/@eggjs/router/badge.svg?style=flat-square)](https://snyk.io/test/npm/@eggjs/router)
8
+
3
9
  Router core component for [Egg.js](https://github.com/eggjs).
4
10
 
5
11
  > **This repository is a fork of [koa-router](https://github.com/alexmingoia/koa-router).** with some additional features.
6
-
7
- > And thanks for the greate work of @alexmingoia and the original team.
12
+ > And thanks for the great work of @alexmingoia and the original team.
8
13
 
9
14
  ## API Reference
10
15
 
11
- * [egg-router](#module_egg-router)
12
- * [Router](#exp_module_egg-router--Router)
13
- * [new Router([opts])](#new_module_egg-router--Router_new)
14
- * _instance_
15
- * [.get|put|post|patch|delete|del](#module_egg-router--Router+get|put|post|patch|delete|del) ⇒ <code>Router</code>
16
- * [.routes](#module_egg-router--Router+routes) ⇒ <code>function</code>
17
- * [.use([path], middleware)](#module_egg-router--Router+use) ⇒ <code>Router</code>
18
- * [.prefix(prefix)](#module_egg-router--Router+prefix) ⇒ <code>Router</code>
19
- * [.allowedMethods([options])](#module_egg-router--Router+allowedMethods) ⇒ <code>function</code>
20
- * [.redirect(source, destination, [code])](#module_egg-router--Router+redirect) ⇒ <code>Router</code>
21
- * [.route(name)](#module_egg-router--Router+route) ⇒ <code>Layer</code> &#124; <code>false</code>
22
- * [.url(name, params, [options])](#module_egg-router--Router+url) ⇒ <code>String</code> &#124; <code>Error</code>
23
- * [.param(param, middleware)](#module_egg-router--Router+param) ⇒ <code>Router</code>
24
- * _static_
25
- * [.url(path, params)](#module_egg-router--Router.url) ⇒ <code>String</code>
16
+ - [@eggjs/router](#eggjsrouter)
17
+ - [API Reference](#api-reference)
18
+ - [Router ](#router-)
19
+ - [new Router(\[opts\])](#new-routeropts)
20
+ - [router.get|put|post|patch|delete|del ⇒ Router](#routergetputpostpatchdeletedel--router)
21
+ - [Named routes](#named-routes)
22
+ - [Multiple middleware](#multiple-middleware)
23
+ - [Nested routers](#nested-routers)
24
+ - [Router prefixes](#router-prefixes)
25
+ - [URL parameters](#url-parameters)
26
+ - [router.routes ⇒ function](#routerroutes--function)
27
+ - [router.use(\[path\], middleware) ⇒ Router](#routerusepath-middleware--router)
28
+ - [router.prefix(prefix) ⇒ Router](#routerprefixprefix--router)
29
+ - [router.allowedMethods(\[options\]) ⇒ function](#routerallowedmethodsoptions--function)
30
+ - [router.redirect(source, destination, \[code\]) ⇒ Router](#routerredirectsource-destination-code--router)
31
+ - [router.route(name) ⇒ Layer | false](#routerroutename--layer--false)
32
+ - [router.url(name, params, \[options\]) ⇒ String | Error](#routerurlname-params-options--string--error)
33
+ - [router.param(param, middleware) ⇒ Router](#routerparamparam-middleware--router)
34
+ - [Router.url(path, params \[, options\]) ⇒ String](#routerurlpath-params--options--string)
35
+ - [Tests](#tests)
36
+ - [Breaking changes on v3](#breaking-changes-on-v3)
37
+ - [License](#license)
26
38
 
27
39
  <a name="exp_module_egg-router--Router"></a>
28
40
 
29
41
  ### Router ⏏
42
+
30
43
  **Kind**: Exported class
31
44
  <a name="new_module_egg-router--Router_new"></a>
32
45
 
33
46
  #### new Router([opts])
34
- Create a new router.
35
47
 
48
+ Create a new router.
36
49
 
37
50
  | Param | Type | Description |
38
- | --- | --- | --- |
51
+ | --- | --- | --- |
39
52
  | [opts] | <code>Object</code> | |
40
53
  | [opts.prefix] | <code>String</code> | prefix router paths |
41
54
 
42
55
  **Example**
43
56
  Basic usage:
44
57
 
45
- ```javascript
46
- var Koa = require('koa');
47
- var Router = require('@eggjs/router');
58
+ ```ts
59
+ import Koa from '@eggjs/koa';
60
+ import Router from '@eggjs/router';
48
61
 
49
- var app = new Koa();
50
- var router = new Router();
62
+ const app = new Koa();
63
+ const router = new Router();
51
64
 
52
- router.get('/', (ctx, next) => {
65
+ router.get('/', async (ctx, next) => {
53
66
  // ctx.router available
54
67
  });
55
68
 
@@ -57,9 +70,11 @@ app
57
70
  .use(router.routes())
58
71
  .use(router.allowedMethods());
59
72
  ```
73
+
60
74
  <a name="module_egg-router--Router+get|put|post|patch|delete|del"></a>
61
75
 
62
76
  #### router.get|put|post|patch|delete|del ⇒ <code>Router</code>
77
+
63
78
  Create `router.verb()` methods, where *verb* is one of the HTTP verbs such
64
79
  as `router.get()` or `router.post()`.
65
80
 
@@ -68,7 +83,7 @@ where **verb** is one of the HTTP verbs such as `router.get()` or `router.post()
68
83
 
69
84
  Additionaly, `router.all()` can be used to match against all methods.
70
85
 
71
- ```javascript
86
+ ```ts
72
87
  router
73
88
  .get('/', (ctx, next) => {
74
89
  ctx.body = 'Hello World!';
@@ -100,7 +115,7 @@ Query strings will not be considered when matching requests.
100
115
  Routes can optionally have names. This allows generation of URLs and easy
101
116
  renaming of URLs during development.
102
117
 
103
- ```javascript
118
+ ```ts
104
119
  router.get('user', '/users/:id', (ctx, next) => {
105
120
  // ...
106
121
  });
@@ -113,7 +128,7 @@ router.url('user', 3);
113
128
 
114
129
  Multiple middleware may be given:
115
130
 
116
- ```javascript
131
+ ```ts
117
132
  router.get(
118
133
  '/users/:id',
119
134
  (ctx, next) => {
@@ -133,9 +148,9 @@ router.get(
133
148
 
134
149
  Nesting routers is supported:
135
150
 
136
- ```javascript
137
- var forums = new Router();
138
- var posts = new Router();
151
+ ```ts
152
+ const forums = new Router();
153
+ const posts = new Router();
139
154
 
140
155
  posts.get('/', (ctx, next) => {...});
141
156
  posts.get('/:pid', (ctx, next) => {...});
@@ -149,8 +164,8 @@ app.use(forums.routes());
149
164
 
150
165
  Route paths can be prefixed at the router level:
151
166
 
152
- ```javascript
153
- var router = new Router({
167
+ ```ts
168
+ const router = new Router({
154
169
  prefix: '/users'
155
170
  });
156
171
 
@@ -162,7 +177,7 @@ router.get('/:id', ...); // responds to "/users/:id"
162
177
 
163
178
  Named route parameters are captured and added to `ctx.params`.
164
179
 
165
- ```javascript
180
+ ```ts
166
181
  router.get('/:category/:title', (ctx, next) => {
167
182
  console.log(ctx.params);
168
183
  // => { category: 'programming', title: 'how-to-node' }
@@ -175,7 +190,7 @@ used to convert paths to regular expressions.
175
190
  **Kind**: instance property of <code>[Router](#exp_module_egg-router--Router)</code>
176
191
 
177
192
  | Param | Type | Description |
178
- | --- | --- | --- |
193
+ | --- | --- | --- |
179
194
  | path | <code>String</code> | |
180
195
  | [middleware] | <code>function</code> | route middleware(s) |
181
196
  | callback | <code>function</code> | route callback |
@@ -189,6 +204,7 @@ Returns router middleware which dispatches a route matching the request.
189
204
  <a name="module_egg-router--Router+use"></a>
190
205
 
191
206
  #### router.use([path], middleware) ⇒ <code>Router</code>
207
+
192
208
  Use given middleware.
193
209
 
194
210
  Middleware run in the order they are defined by `.use()`. They are invoked
@@ -204,7 +220,8 @@ sequentially, requests start at the first middleware and work their way
204
220
  | [...] | <code>function</code> |
205
221
 
206
222
  **Example**
207
- ```javascript
223
+
224
+ ```ts
208
225
  // session middleware will run before authorize
209
226
  router
210
227
  .use(session())
@@ -218,9 +235,11 @@ router.use(['/users', '/admin'], userAuth());
218
235
 
219
236
  app.use(router.routes());
220
237
  ```
238
+
221
239
  <a name="module_egg-router--Router+prefix"></a>
222
240
 
223
241
  #### router.prefix(prefix) ⇒ <code>Router</code>
242
+
224
243
  Set the path prefix for a Router instance that was already initialized.
225
244
 
226
245
  **Kind**: instance method of <code>[Router](#exp_module_egg-router--Router)</code>
@@ -230,12 +249,15 @@ Set the path prefix for a Router instance that was already initialized.
230
249
  | prefix | <code>String</code> |
231
250
 
232
251
  **Example**
233
- ```javascript
252
+
253
+ ```ts
234
254
  router.prefix('/things/:thing_id')
235
255
  ```
256
+
236
257
  <a name="module_egg-router--Router+allowedMethods"></a>
237
258
 
238
259
  #### router.allowedMethods([options]) ⇒ <code>function</code>
260
+
239
261
  Returns separate middleware for responding to `OPTIONS` requests with
240
262
  an `Allow` header containing the allowed methods, as well as responding
241
263
  with `405 Method Not Allowed` and `501 Not Implemented` as appropriate.
@@ -250,12 +272,13 @@ with `405 Method Not Allowed` and `501 Not Implemented` as appropriate.
250
272
  | [options.methodNotAllowed] | <code>function</code> | throw the returned value in place of the default MethodNotAllowed error |
251
273
 
252
274
  **Example**
253
- ```javascript
254
- var Koa = require('koa');
255
- var Router = require('egg-router');
256
275
 
257
- var app = new Koa();
258
- var router = new Router();
276
+ ```ts
277
+ import Koa from '@eggjs/koa';
278
+ import Router from '@eggjs/router';
279
+
280
+ const app = new Koa();
281
+ const router = new Router();
259
282
 
260
283
  app.use(router.routes());
261
284
  app.use(router.allowedMethods());
@@ -263,13 +286,13 @@ app.use(router.allowedMethods());
263
286
 
264
287
  **Example with [Boom](https://github.com/hapijs/boom)**
265
288
 
266
- ```javascript
267
- var Koa = require('koa');
268
- var Router = require('egg-router');
269
- var Boom = require('boom');
289
+ ```ts
290
+ import Koa from '@eggjs/koa';
291
+ import Router from '@eggjs/router';
292
+ import Boom from 'boom';
270
293
 
271
- var app = new Koa();
272
- var router = new Router();
294
+ const app = new Koa();
295
+ const router = new Router();
273
296
 
274
297
  app.use(router.routes());
275
298
  app.use(router.allowedMethods({
@@ -278,9 +301,11 @@ app.use(router.allowedMethods({
278
301
  methodNotAllowed: () => new Boom.methodNotAllowed()
279
302
  }));
280
303
  ```
304
+
281
305
  <a name="module_egg-router--Router+redirect"></a>
282
306
 
283
307
  #### router.redirect(source, destination, [code]) ⇒ <code>Router</code>
308
+
284
309
  Redirect `source` to `destination` URL with optional 30x status `code`.
285
310
 
286
311
  Both `source` and `destination` can be route names.
@@ -291,7 +316,7 @@ router.redirect('/login', 'sign-in');
291
316
 
292
317
  This is equivalent to:
293
318
 
294
- ```javascript
319
+ ```ts
295
320
  router.all('/login', ctx => {
296
321
  ctx.redirect('/sign-in');
297
322
  ctx.status = 301;
@@ -309,6 +334,7 @@ router.all('/login', ctx => {
309
334
  <a name="module_egg-router--Router+route"></a>
310
335
 
311
336
  #### router.route(name) ⇒ <code>Layer</code> &#124; <code>false</code>
337
+
312
338
  Lookup route with given `name`.
313
339
 
314
340
  **Kind**: instance method of <code>[Router](#exp_module_egg-router--Router)</code>
@@ -320,6 +346,7 @@ Lookup route with given `name`.
320
346
  <a name="module_egg-router--Router+url"></a>
321
347
 
322
348
  #### router.url(name, params, [options]) ⇒ <code>String</code> &#124; <code>Error</code>
349
+
323
350
  Generate URL for route. Takes a route name and map of named `params`.
324
351
 
325
352
  **Kind**: instance method of <code>[Router](#exp_module_egg-router--Router)</code>
@@ -332,7 +359,8 @@ Generate URL for route. Takes a route name and map of named `params`.
332
359
  | [options.query] | <code>Object</code> &#124; <code>String</code> | query options |
333
360
 
334
361
  **Example**
335
- ```javascript
362
+
363
+ ```ts
336
364
  router.get('user', '/users/:id', (ctx, next) => {
337
365
  // ...
338
366
  });
@@ -354,9 +382,11 @@ router.url('user', { id: 3 }, { query: { limit: 1 } });
354
382
  router.url('user', { id: 3 }, { query: "limit=1" });
355
383
  // => "/users/3?limit=1"
356
384
  ```
385
+
357
386
  <a name="module_egg-router--Router+param"></a>
358
387
 
359
388
  #### router.param(param, middleware) ⇒ <code>Router</code>
389
+
360
390
  Run middleware for named route parameters. Useful for auto-loading or
361
391
  validation.
362
392
 
@@ -368,7 +398,8 @@ validation.
368
398
  | middleware | <code>function</code> |
369
399
 
370
400
  **Example**
371
- ```javascript
401
+
402
+ ```ts
372
403
  router
373
404
  .param('user', (id, ctx, next) => {
374
405
  ctx.user = users[id];
@@ -386,9 +417,11 @@ router
386
417
  // /users/3 => {"id": 3, "name": "Alex"}
387
418
  // /users/3/friends => [{"id": 4, "name": "TJ"}]
388
419
  ```
420
+
389
421
  <a name="module_egg-router--Router.url"></a>
390
422
 
391
423
  #### Router.url(path, params [, options]) ⇒ <code>String</code>
424
+
392
425
  Generate URL from url pattern and given `params`.
393
426
 
394
427
  **Kind**: static method of <code>[Router](#exp_module_egg-router--Router)</code>
@@ -401,8 +434,9 @@ Generate URL from url pattern and given `params`.
401
434
  | [options.query] | <code>Object</code> &#124; <code>String</code> | query options |
402
435
 
403
436
  **Example**
404
- ```javascript
405
- var url = Router.url('/users/:id', {id: 1});
437
+
438
+ ```ts
439
+ const url = Router.url('/users/:id', {id: 1});
406
440
  // => "/users/1"
407
441
 
408
442
  const url = Router.url('/users/:id', {id: 1}, {query: { active: true }});
@@ -412,3 +446,12 @@ const url = Router.url('/users/:id', {id: 1}, {query: { active: true }});
412
446
  ## Tests
413
447
 
414
448
  Run tests using `npm test`.
449
+
450
+ ## Breaking changes on v3
451
+
452
+ - Drop generator function support
453
+ - Drop Node.js < 18.7.0 support
454
+
455
+ ## License
456
+
457
+ [MIT](LICENSE)
@@ -0,0 +1,102 @@
1
+ import { RegisterOptions, Router, RouterMethod, RouterOptions } from './Router.js';
2
+ import { MiddlewareFunc, ResourcesController } from './types.js';
3
+ interface Application {
4
+ controller: Record<string, any>;
5
+ }
6
+ /**
7
+ * FIXME: move these patch into @eggjs/router
8
+ */
9
+ export declare class EggRouter extends Router {
10
+ readonly app: Application;
11
+ /**
12
+ * @class
13
+ * @param {Object} opts - Router options.
14
+ * @param {Application} app - Application object.
15
+ */
16
+ constructor(opts: RouterOptions, app: Application);
17
+ verb(method: RouterMethod | RouterMethod[], nameOrPath: string | RegExp | (string | RegExp)[], pathOrMiddleware: string | RegExp | (string | RegExp)[] | MiddlewareFunc, ...middleware: (MiddlewareFunc | string)[]): this;
18
+ head(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): Router;
19
+ head(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): Router;
20
+ options(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): Router;
21
+ options(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): Router;
22
+ get(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): Router;
23
+ get(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): Router;
24
+ put(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): Router;
25
+ put(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): Router;
26
+ patch(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): Router;
27
+ patch(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): Router;
28
+ post(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): Router;
29
+ post(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): Router;
30
+ delete(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): Router;
31
+ delete(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): Router;
32
+ all(path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): Router;
33
+ all(name: string, path: string | RegExp | (string | RegExp)[], ...middlewares: (MiddlewareFunc | string)[]): Router;
34
+ register(path: string | RegExp | (string | RegExp)[], methods: string[], middleware: MiddlewareFunc | string | (MiddlewareFunc | string | ResourcesController)[], opts?: RegisterOptions): import("./Layer.js").Layer | import("./Layer.js").Layer[];
35
+ /**
36
+ * restful router api
37
+ * @param {String} name - Router name
38
+ * @param {String} prefix - url prefix
39
+ * @param {Function} middleware - middleware or controller
40
+ * @example
41
+ * ```js
42
+ * app.resources('/posts', 'posts')
43
+ * app.resources('posts', '/posts', 'posts')
44
+ * app.resources('posts', '/posts', app.role.can('user'), app.controller.posts)
45
+ * ```
46
+ *
47
+ * Examples:
48
+ *
49
+ * ```js
50
+ * app.resources('/posts', 'posts')
51
+ * ```
52
+ *
53
+ * yield router mapping
54
+ *
55
+ * Method | Path | Route Name | Controller.Action
56
+ * -------|-----------------|----------------|-----------------------------
57
+ * GET | /posts | posts | app.controller.posts.index
58
+ * GET | /posts/new | new_post | app.controller.posts.new
59
+ * GET | /posts/:id | post | app.controller.posts.show
60
+ * GET | /posts/:id/edit | edit_post | app.controller.posts.edit
61
+ * POST | /posts | posts | app.controller.posts.create
62
+ * PATCH | /posts/:id | post | app.controller.posts.update
63
+ * DELETE | /posts/:id | post | app.controller.posts.destroy
64
+ *
65
+ * app.router.url can generate url based on arguments
66
+ * ```js
67
+ * app.router.url('posts')
68
+ * => /posts
69
+ * app.router.url('post', { id: 1 })
70
+ * => /posts/1
71
+ * app.router.url('new_post')
72
+ * => /posts/new
73
+ * app.router.url('edit_post', { id: 1 })
74
+ * => /posts/1/edit
75
+ * ```
76
+ * @return {Router} return route object.
77
+ * @since 1.0.0
78
+ */
79
+ resources(prefix: string, controller: string | ResourcesController): Router;
80
+ resources(prefix: string, middleware: MiddlewareFunc, controller: string | ResourcesController): Router;
81
+ resources(name: string, prefix: string, controller: string | ResourcesController): Router;
82
+ resources(name: string, prefix: string, middleware: MiddlewareFunc, controller: string | ResourcesController): Router;
83
+ /**
84
+ * @param {String} name - Router name
85
+ * @param {Object} params - more parameters
86
+ * @example
87
+ * ```js
88
+ * router.url('edit_post', { id: 1, name: 'foo', page: 2 })
89
+ * => /posts/1/edit?name=foo&page=2
90
+ * router.url('posts', { name: 'foo&1', page: 2 })
91
+ * => /posts?name=foo%261&page=2
92
+ * ```
93
+ * @return {String} url by path name and query params.
94
+ * @since 1.0.0
95
+ */
96
+ url(name: string, params?: Record<string, string | number | (string | number)[]>): string;
97
+ /**
98
+ * @alias to url()
99
+ */
100
+ pathFor(name: string, params?: Record<string, string | number | (string | number)[]>): string;
101
+ }
102
+ export {};