Skip to content

feat: add convenience function for adding multiple routes #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,7 @@ middleware, error handling, api fields / returning extraction).

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

const router = new Router();

Expand All @@ -506,6 +506,21 @@ addRouteToRouter(
router,
);

// or

addRoutesToRouter(router, [
route({
path: '/my-route',
method: HttpMethod.GET,
async action() {
return {
foo: 'bar',
bar: 'baz',
};
},
}),
]);

export default router;
```

Expand Down
40 changes: 40 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
bindRouteActions,
createAllRoutes,
addRouteToRouter,
addRoutesToRouter,
createOpenAPI,
propagateErrors,
propagateValues,
Expand Down Expand Up @@ -1442,6 +1443,45 @@ test('addRouteToRouter', async () => {
server.close();
});

test('addRoutesToRouter', async () => {
const app = new Koa();
const router = new Router();

addRoutesToRouter(router, [
route({
path: '/first',
method: HttpMethod.GET,
async action() {
return 'first';
},
}),
route({
path: '/second',
method: HttpMethod.GET,
async action() {
return 'second';
},
}),
]);

app.use(router.routes()).use(router.allowedMethods());

const server = createServer(app.callback());
const test = agent(server);

await test
.get('/first')
.expect(200)
.expect('first');

await test
.get('/second')
.expect(200)
.expect('second');

server.close();
});

test('lazy route middleware', async () => {
const factory: RouteFactory<{}> = {
getDependencies() {
Expand Down
7 changes: 7 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -721,6 +721,13 @@ export const addRouteToRouter = (route: Route | MadeRoute, router: Router) => {
});
};

export const addRoutesToRouter = (router: Router, routes: (Route | MadeRoute)[]) => {
for (const route of routes) {
addRouteToRouter(route, router);
}
return router;
};

function filterInternalMessages(
status: number,
errorMessage: string,
Expand Down