Files
foka-ci/apps/server/controllers/application.ts
hurole 63c1e4df63 feat: 添加路由装饰器系统和全局异常处理
- 新增装饰器支持(@Get, @Post, @Put, @Delete, @Patch, @Controller)
- 实现路由自动注册机制(RouteScanner)
- 添加全局异常处理中间件(Exception)
- 实现统一响应体格式(ApiResponse)
- 新增请求体解析中间件(BodyParser)
- 重构控制器为类模式,支持装饰器路由
- 添加示例用户控制器(UserController)
- 更新TypeScript配置支持装饰器
- 添加reflect-metadata依赖
- 完善项目文档

Breaking Changes:
- 控制器现在返回数据而不是直接设置ctx.body
- 新增统一的API响应格式
2025-09-01 00:14:17 +08:00

51 lines
1.4 KiB
TypeScript

import type { Context } from 'koa';
import prisma from '../libs/db.ts';
import { BusinessError } from '../middlewares/exception.ts';
import { Controller, Get } from '../decorators/route.ts';
@Controller('/application')
export class ApplicationController {
@Get('/list')
async list(ctx: Context) {
try {
const list = await prisma.application.findMany({
where: {
valid: 1,
},
});
// 直接返回数据,由路由中间件统一包装成响应格式
return list;
} catch (error) {
// 抛出业务异常,由全局异常处理中间件捕获
throw new BusinessError('获取应用列表失败', 1001, 500);
}
}
@Get('/detail/:id')
async detail(ctx: Context) {
try {
const { id } = ctx.params;
const app = await prisma.application.findUnique({
where: { id: Number(id) },
});
if (!app) {
throw new BusinessError('应用不存在', 1002, 404);
}
return app;
} catch (error) {
if (error instanceof BusinessError) {
throw error;
}
throw new BusinessError('获取应用详情失败', 1003, 500);
}
}
}
// 保持向后兼容的导出方式
const applicationController = new ApplicationController();
export const list = applicationController.list.bind(applicationController);
export const detail = applicationController.detail.bind(applicationController);