我使用express初始化了typeorm
(0.2.17版),给出了一个基本的示例项目。我在./src/routes.ts
中如何使用./src/index.ts
中的routes数组时遇到麻烦,但是我喜欢数组中的route对象使用控制器。有没有一种更简单的方式以这种方式进行路由?
./src/routes.ts
中的路由数组如下:
import {UserController} from "./controllers/UserController";
export const Routes = [{
method: "get",
route: "/users",
controller: UserController,
action: "all"
}, {
method: "get",
route: "/users/:id",
controller: UserController,
action: "one"
}, {
method: "post",
route: "/users",
controller: UserController,
action: "save"
}, {
method: "delete",
route: "/users/:id",
controller: UserController,
action: "remove"
}];
这就是在./src/index.ts
...
import {Routes} from "./routes";
...
// register express routes from defined application routes
Routes.forEach(route => {
(app as any)[route.method](route.route, (req: Request, res: Response, next: Function) => {
const result = (new (route.controller as any))[route.action](req, res, next);
if (result instanceof Promise) {
result.then(result => result !== null && result !== undefined ? res.send(result) : undefined);
} else if (result !== null && result !== undefined) {
res.json(result);
}
});
});
...