gpt4 book ai didi

typescript - 如何将分离的 Koa-Router 与 Typescript 结合起来

转载 作者:行者123 更新时间:2023-12-04 01:41:12 26 4
gpt4 key购买 nike

我决定按用途拆分我的路由器,所以它们看起来像这样:

routers/homeRouter.ts

import * as Router from 'koa-router';

const router: Router = new Router();

router
.get('/', async (ctx, next) => {
ctx.body = 'hello world';
});

export = router;

routers/userRouter.ts

import * as Router from 'koa-router';
import UserController = require('../controller/userController');

const router: Router = new Router(
{
prefix: 'users'
}
);

var userController = new UserController();

router
.post('/user/:email/:password', userController.signUp);

export = router;

有了这个,我的 app.ts 必须像这样一个一个地导入每个路由器:

app.ts

import * as Koa from 'koa';
import * as homeRouter from './routers/homeRouter';
import * as userRouter from './routers/userRouter';
const app: Koa = new Koa();
app
.use(homeRouter.routes())
.use(homeRouter.allowedMethods());
app
.use(userRouter.routes())
.use(userRouter.allowedMethods());
app.listen(3000);

但我想要的是:

app.ts

import * as Koa from 'koa';
import * as routers from './routers';
const app: Koa = new Koa();
app
.use(routers.routes())
.use(routers.allowedMethods());
app.listen(3000);

我不知道如何导出路由器来实现这一点。谁能帮忙?

最佳答案

你可以有这样的东西:

userRouter.ts

import * as Router from 'koa-router';

const router = new Router();
router.get('/', list);

...

export default router.routes();

routes.ts

import * as Router from 'koa-router';


import UserRouter from './userRouter';
import HomeRouter from './homeRouter';

const apiRouter = new Router({ prefix: '/api'});
apiRouter.use('/users', UserRouter);
apiRouter.use('/home', HomeRouter);

export default apiRouter.routes();

您可以像您所做的那样分别实现每个路由器,然后生成一个包含所有路由器的新路由器。然后您可以将其包含在您的 app.ts 文件中。

关于typescript - 如何将分离的 Koa-Router 与 Typescript 结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46754169/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com