Skip to content

Commit 55149bc

Browse files
authored
feat: support cjs and esm both (#10)
BREAKING CHANGE: drop Node.js < 18.7.0 support - Drop generator function support - Drop Node.js < 18.7.0 support <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Introduced `EggRouter` class for defining RESTful routes and handling HTTP verbs. - Added new utility functions and type definitions to support enhanced routing and middleware functionalities. - **Bug Fixes** - Updated test cases to ensure compatibility with new routing and middleware functionalities. - **Documentation** - Updated examples in the `README.md` to reflect TypeScript syntax and ES module imports. - Mentioned breaking changes for version 3, including dropping support for generator functions and Node.js versions below 18.7.0. - **Breaking Changes** - Dropped support for generator functions. - Dropped support for Node.js versions below 18.7.0. - **Chores** - Updated Node.js versions in the GitHub Actions workflow. - Modified `.gitignore` to include additional patterns. - Updated dependencies and dev dependencies in `package.json`. - Added new scripts for linting, testing, and pre-publish actions in `package.json`. - Introduced a new `tsconfig.json` for strict TypeScript settings. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 2d71fd8 commit 55149bc

26 files changed

Lines changed: 2595 additions & 2456 deletions

.eslintrc

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
11
{
2-
"extends": "eslint-config-egg"
2+
"extends": [
3+
"eslint-config-egg/typescript",
4+
"eslint-config-egg/lib/rules/enforce-node-prefix"
5+
]
36
}

.github/workflows/nodejs.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,6 @@ jobs:
1212
uses: node-modules/github-actions/.github/workflows/node-test.yml@master
1313
with:
1414
os: 'ubuntu-latest'
15-
version: '8, 10, 12, 14, 16, 18, 20, 22'
15+
version: '18.7.0, 18, 20, 22'
1616
secrets:
1717
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,6 @@ yarn.lock
4242
!.env.test
4343

4444
.DS_Store
45+
46+
.tshy*
47+
dist
File renamed without changes.

README.md

Lines changed: 64 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -27,44 +27,48 @@ Router core component for [Egg.js](https://github.com/eggjs).
2727
- [router.param(param, middleware) ⇒ Router](#routerparamparam-middleware--router)
2828
- [Router.url(path, params \[, options\]) ⇒ String](#routerurlpath-params--options--string)
2929
- [Tests](#tests)
30+
- [Breaking changes on v3](#breaking-changes-on-v3)
3031
- [License](#license)
3132

3233
<a name="exp_module_egg-router--Router"></a>
3334

3435
### Router ⏏
36+
3537
**Kind**: Exported class
3638
<a name="new_module_egg-router--Router_new"></a>
3739

3840
#### new Router([opts])
39-
Create a new router.
4041

42+
Create a new router.
4143

4244
| Param | Type | Description |
43-
| --- | --- | --- |
45+
| --- | --- | --- |
4446
| [opts] | <code>Object</code> | |
4547
| [opts.prefix] | <code>String</code> | prefix router paths |
4648

4749
**Example**
4850
Basic usage:
4951

50-
```javascript
51-
var Koa = require('koa');
52-
var Router = require('@eggjs/router');
52+
```ts
53+
import Koa from '@eggjs/koa';
54+
import Router from '@eggjs/router';
5355

54-
var app = new Koa();
55-
var router = new Router();
56+
const app = new Koa();
57+
const router = new Router();
5658

57-
router.get('/', (ctx, next) => {
59+
router.get('/', async (ctx, next) => {
5860
// ctx.router available
5961
});
6062

6163
app
6264
.use(router.routes())
6365
.use(router.allowedMethods());
6466
```
67+
6568
<a name="module_egg-router--Router+get|put|post|patch|delete|del"></a>
6669

6770
#### router.get|put|post|patch|delete|del ⇒ <code>Router</code>
71+
6872
Create `router.verb()` methods, where *verb* is one of the HTTP verbs such
6973
as `router.get()` or `router.post()`.
7074

@@ -73,7 +77,7 @@ where **verb** is one of the HTTP verbs such as `router.get()` or `router.post()
7377

7478
Additionaly, `router.all()` can be used to match against all methods.
7579

76-
```javascript
80+
```ts
7781
router
7882
.get('/', (ctx, next) => {
7983
ctx.body = 'Hello World!';
@@ -105,7 +109,7 @@ Query strings will not be considered when matching requests.
105109
Routes can optionally have names. This allows generation of URLs and easy
106110
renaming of URLs during development.
107111

108-
```javascript
112+
```ts
109113
router.get('user', '/users/:id', (ctx, next) => {
110114
// ...
111115
});
@@ -118,7 +122,7 @@ router.url('user', 3);
118122

119123
Multiple middleware may be given:
120124

121-
```javascript
125+
```ts
122126
router.get(
123127
'/users/:id',
124128
(ctx, next) => {
@@ -138,9 +142,9 @@ router.get(
138142

139143
Nesting routers is supported:
140144

141-
```javascript
142-
var forums = new Router();
143-
var posts = new Router();
145+
```ts
146+
const forums = new Router();
147+
const posts = new Router();
144148

145149
posts.get('/', (ctx, next) => {...});
146150
posts.get('/:pid', (ctx, next) => {...});
@@ -154,8 +158,8 @@ app.use(forums.routes());
154158

155159
Route paths can be prefixed at the router level:
156160

157-
```javascript
158-
var router = new Router({
161+
```ts
162+
const router = new Router({
159163
prefix: '/users'
160164
});
161165

@@ -167,7 +171,7 @@ router.get('/:id', ...); // responds to "/users/:id"
167171

168172
Named route parameters are captured and added to `ctx.params`.
169173

170-
```javascript
174+
```ts
171175
router.get('/:category/:title', (ctx, next) => {
172176
console.log(ctx.params);
173177
// => { category: 'programming', title: 'how-to-node' }
@@ -180,7 +184,7 @@ used to convert paths to regular expressions.
180184
**Kind**: instance property of <code>[Router](#exp_module_egg-router--Router)</code>
181185

182186
| Param | Type | Description |
183-
| --- | --- | --- |
187+
| --- | --- | --- |
184188
| path | <code>String</code> | |
185189
| [middleware] | <code>function</code> | route middleware(s) |
186190
| callback | <code>function</code> | route callback |
@@ -194,6 +198,7 @@ Returns router middleware which dispatches a route matching the request.
194198
<a name="module_egg-router--Router+use"></a>
195199

196200
#### router.use([path], middleware) ⇒ <code>Router</code>
201+
197202
Use given middleware.
198203

199204
Middleware run in the order they are defined by `.use()`. They are invoked
@@ -209,7 +214,8 @@ sequentially, requests start at the first middleware and work their way
209214
| [...] | <code>function</code> |
210215

211216
**Example**
212-
```javascript
217+
218+
```ts
213219
// session middleware will run before authorize
214220
router
215221
.use(session())
@@ -223,9 +229,11 @@ router.use(['/users', '/admin'], userAuth());
223229

224230
app.use(router.routes());
225231
```
232+
226233
<a name="module_egg-router--Router+prefix"></a>
227234

228235
#### router.prefix(prefix) ⇒ <code>Router</code>
236+
229237
Set the path prefix for a Router instance that was already initialized.
230238

231239
**Kind**: instance method of <code>[Router](#exp_module_egg-router--Router)</code>
@@ -235,12 +243,15 @@ Set the path prefix for a Router instance that was already initialized.
235243
| prefix | <code>String</code> |
236244

237245
**Example**
238-
```javascript
246+
247+
```ts
239248
router.prefix('/things/:thing_id')
240249
```
250+
241251
<a name="module_egg-router--Router+allowedMethods"></a>
242252

243253
#### router.allowedMethods([options]) ⇒ <code>function</code>
254+
244255
Returns separate middleware for responding to `OPTIONS` requests with
245256
an `Allow` header containing the allowed methods, as well as responding
246257
with `405 Method Not Allowed` and `501 Not Implemented` as appropriate.
@@ -255,26 +266,27 @@ with `405 Method Not Allowed` and `501 Not Implemented` as appropriate.
255266
| [options.methodNotAllowed] | <code>function</code> | throw the returned value in place of the default MethodNotAllowed error |
256267

257268
**Example**
258-
```javascript
259-
var Koa = require('koa');
260-
var Router = require('egg-router');
261269

262-
var app = new Koa();
263-
var router = new Router();
270+
```ts
271+
import Koa from '@eggjs/koa';
272+
import Router from '@eggjs/router';
273+
274+
const app = new Koa();
275+
const router = new Router();
264276

265277
app.use(router.routes());
266278
app.use(router.allowedMethods());
267279
```
268280

269281
**Example with [Boom](https://github.com/hapijs/boom)**
270282

271-
```javascript
272-
var Koa = require('koa');
273-
var Router = require('egg-router');
274-
var Boom = require('boom');
283+
```ts
284+
import Koa from '@eggjs/koa';
285+
import Router from '@eggjs/router';
286+
import Boom from 'boom';
275287

276-
var app = new Koa();
277-
var router = new Router();
288+
const app = new Koa();
289+
const router = new Router();
278290

279291
app.use(router.routes());
280292
app.use(router.allowedMethods({
@@ -283,9 +295,11 @@ app.use(router.allowedMethods({
283295
methodNotAllowed: () => new Boom.methodNotAllowed()
284296
}));
285297
```
298+
286299
<a name="module_egg-router--Router+redirect"></a>
287300

288301
#### router.redirect(source, destination, [code]) ⇒ <code>Router</code>
302+
289303
Redirect `source` to `destination` URL with optional 30x status `code`.
290304

291305
Both `source` and `destination` can be route names.
@@ -296,7 +310,7 @@ router.redirect('/login', 'sign-in');
296310

297311
This is equivalent to:
298312

299-
```javascript
313+
```ts
300314
router.all('/login', ctx => {
301315
ctx.redirect('/sign-in');
302316
ctx.status = 301;
@@ -314,6 +328,7 @@ router.all('/login', ctx => {
314328
<a name="module_egg-router--Router+route"></a>
315329

316330
#### router.route(name) ⇒ <code>Layer</code> &#124; <code>false</code>
331+
317332
Lookup route with given `name`.
318333

319334
**Kind**: instance method of <code>[Router](#exp_module_egg-router--Router)</code>
@@ -325,6 +340,7 @@ Lookup route with given `name`.
325340
<a name="module_egg-router--Router+url"></a>
326341

327342
#### router.url(name, params, [options]) ⇒ <code>String</code> &#124; <code>Error</code>
343+
328344
Generate URL for route. Takes a route name and map of named `params`.
329345

330346
**Kind**: instance method of <code>[Router](#exp_module_egg-router--Router)</code>
@@ -337,7 +353,8 @@ Generate URL for route. Takes a route name and map of named `params`.
337353
| [options.query] | <code>Object</code> &#124; <code>String</code> | query options |
338354

339355
**Example**
340-
```javascript
356+
357+
```ts
341358
router.get('user', '/users/:id', (ctx, next) => {
342359
// ...
343360
});
@@ -359,9 +376,11 @@ router.url('user', { id: 3 }, { query: { limit: 1 } });
359376
router.url('user', { id: 3 }, { query: "limit=1" });
360377
// => "/users/3?limit=1"
361378
```
379+
362380
<a name="module_egg-router--Router+param"></a>
363381

364382
#### router.param(param, middleware) ⇒ <code>Router</code>
383+
365384
Run middleware for named route parameters. Useful for auto-loading or
366385
validation.
367386

@@ -373,7 +392,8 @@ validation.
373392
| middleware | <code>function</code> |
374393

375394
**Example**
376-
```javascript
395+
396+
```ts
377397
router
378398
.param('user', (id, ctx, next) => {
379399
ctx.user = users[id];
@@ -391,9 +411,11 @@ router
391411
// /users/3 => {"id": 3, "name": "Alex"}
392412
// /users/3/friends => [{"id": 4, "name": "TJ"}]
393413
```
414+
394415
<a name="module_egg-router--Router.url"></a>
395416

396417
#### Router.url(path, params [, options]) ⇒ <code>String</code>
418+
397419
Generate URL from url pattern and given `params`.
398420

399421
**Kind**: static method of <code>[Router](#exp_module_egg-router--Router)</code>
@@ -406,8 +428,9 @@ Generate URL from url pattern and given `params`.
406428
| [options.query] | <code>Object</code> &#124; <code>String</code> | query options |
407429

408430
**Example**
409-
```javascript
410-
var url = Router.url('/users/:id', {id: 1});
431+
432+
```ts
433+
const url = Router.url('/users/:id', {id: 1});
411434
// => "/users/1"
412435

413436
const url = Router.url('/users/:id', {id: 1}, {query: { active: true }});
@@ -418,6 +441,11 @@ const url = Router.url('/users/:id', {id: 1}, {query: { active: true }});
418441

419442
Run tests using `npm test`.
420443

444+
## Breaking changes on v3
445+
446+
- Drop generator function support
447+
- Drop Node.js < 18.7.0 support
448+
421449
## License
422450

423451
[MIT](LICENSE)

bench/run

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ export PORT=3333
88

99
host="http://localhost:$PORT"
1010

11-
node "$(dirname $0)/server.js" &
11+
node "$(dirname $0)/server.cjs" &
1212

1313
pid=$!
1414

bench/server.js renamed to bench/server.cjs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
'use strict';
1+
/* eslint-disable @typescript-eslint/no-var-requires */
2+
const { Application } = require('@eggjs/koa');
3+
const { Router } = require('../dist/commonjs');
24

3-
const Koa = require('koa');
4-
const Router = require('../');
5-
6-
const app = new Koa();
5+
const app = new Application();
76
const router = new Router();
87

98
const ok = ctx => {
@@ -36,8 +35,8 @@ for (let i = n; i > 0; i--) {
3635
const child = new Router();
3736
if (useMiddleware) child.use((ctx, next) => next());
3837
child.get(`/:${''.padStart(i, 'a')}`, ok);
39-
child.nest('/grandchild', grandchild);
40-
router.nest(`/${i}/child`, child);
38+
// child.use('/grandchild', grandchild);
39+
// router.use(`/${i}/child`, child);
4140
}
4241

4342
if (process.env.DEBUG) {

index.js

Lines changed: 0 additions & 10 deletions
This file was deleted.

0 commit comments

Comments
 (0)