Skip to content

Commit 119035c

Browse files
committed
feat: add convenience function for adding multiple routes
1 parent e6265e6 commit 119035c

File tree

3 files changed

+63
-1
lines changed

3 files changed

+63
-1
lines changed

README.md

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -485,7 +485,7 @@ middleware, error handling, api fields / returning extraction).
485485

486486
```typescript
487487
import * as Router from 'koa-router';
488-
import { route, addRouteToRouter, HttpMethod } from '@lcdev/router';
488+
import { route, addRouteToRouter, addRoutesToRouter, HttpMethod } from '@lcdev/router';
489489

490490
const router = new Router();
491491

@@ -506,6 +506,21 @@ addRouteToRouter(
506506
router,
507507
);
508508

509+
// or
510+
511+
addRoutesToRouter(router, [
512+
route({
513+
path: '/my-route',
514+
method: HttpMethod.GET,
515+
async action() {
516+
return {
517+
foo: 'bar',
518+
bar: 'baz',
519+
};
520+
},
521+
}),
522+
]);
523+
509524
export default router;
510525
```
511526

src/index.test.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
bindRouteActions,
2020
createAllRoutes,
2121
addRouteToRouter,
22+
addRoutesToRouter,
2223
createOpenAPI,
2324
propagateErrors,
2425
propagateValues,
@@ -1442,6 +1443,45 @@ test('addRouteToRouter', async () => {
14421443
server.close();
14431444
});
14441445

1446+
test('addRoutesToRouter', async () => {
1447+
const app = new Koa();
1448+
const router = new Router();
1449+
1450+
addRoutesToRouter(router, [
1451+
route({
1452+
path: '/first',
1453+
method: HttpMethod.GET,
1454+
async action() {
1455+
return 'first';
1456+
},
1457+
}),
1458+
route({
1459+
path: '/second',
1460+
method: HttpMethod.GET,
1461+
async action() {
1462+
return 'second';
1463+
},
1464+
}),
1465+
]);
1466+
1467+
app.use(router.routes()).use(router.allowedMethods());
1468+
1469+
const server = createServer(app.callback());
1470+
const test = agent(server);
1471+
1472+
await test
1473+
.get('/first')
1474+
.expect(200)
1475+
.expect('first');
1476+
1477+
await test
1478+
.get('/second')
1479+
.expect(200)
1480+
.expect('second');
1481+
1482+
server.close();
1483+
});
1484+
14451485
test('lazy route middleware', async () => {
14461486
const factory: RouteFactory<{}> = {
14471487
getDependencies() {

src/index.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,13 @@ export const addRouteToRouter = (route: Route | MadeRoute, router: Router) => {
721721
});
722722
};
723723

724+
export const addRoutesToRouter = (router: Router, routes: (Route | MadeRoute)[]) => {
725+
for (const route of routes) {
726+
addRouteToRouter(route, router);
727+
}
728+
return router;
729+
};
730+
724731
function filterInternalMessages(
725732
status: number,
726733
errorMessage: string,

0 commit comments

Comments
 (0)