Files
foka-ci/apps/server/middlewares/body-parser.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

47 lines
1.2 KiB
TypeScript

import type Koa from 'koa';
import type { Middleware } from './types.ts';
/**
* 请求体解析中间件
*/
export class BodyParser implements Middleware {
apply(app: Koa): void {
// 使用动态导入来避免类型问题
app.use(async (ctx, next) => {
if (ctx.request.method === 'POST' ||
ctx.request.method === 'PUT' ||
ctx.request.method === 'PATCH') {
// 简单的JSON解析
if (ctx.request.type === 'application/json') {
try {
const chunks: Buffer[] = [];
ctx.req.on('data', (chunk) => {
chunks.push(chunk);
});
await new Promise((resolve) => {
ctx.req.on('end', () => {
const body = Buffer.concat(chunks).toString();
try {
(ctx.request as any).body = JSON.parse(body);
} catch {
(ctx.request as any).body = {};
}
resolve(void 0);
});
});
} catch (error) {
(ctx.request as any).body = {};
}
} else {
(ctx.request as any).body = {};
}
}
await next();
});
}
}