@studiogm/bara-core
v1.0.1
Published
一个基于TypeScript装饰器的Koa路由框架,具有完整的中间件兼容性
Maintainers
Readme
Koa装饰器路由框架
一个基于Koa的TypeScript装饰器路由框架,提供优雅的装饰器语法和完整的类型安全支持。
✨ 特性
🚀 核心功能
- 🎯 TypeScript装饰器语法 - 使用@Get、@Post等装饰器定义路由
- 🛡️ 完整类型安全 - 全面的TypeScript类型支持和推断
- 🔗 Koa中间件兼容 - 完全兼容Koa生态系统
- 📦 多格式打包 - 支持CommonJS和ES Module
- 🚀 应用级别装饰器 - 提供@App、@Listen等高级装饰器
- 🎨 参数注入 - 支持@Param、@Query、@Body等参数装饰器
- 🌐 路由参数 - 支持动态路由如/user/:id
- ⚡ 中间件链 - 支持Koa洋葱模型中间件
🔒 安全特性 (v1.1.0+)
- 🛡️ 安全JSON解析 - 防护原型污染攻击
- 🚫 请求体大小限制 - 防护DoS攻击
- 🌐 加强CORS配置 - 严格的跨域安全控制
- 🔐 输入验证框架 - 基于Joi的强大验证系统
- 🛡️ 安全中间件套件 - 速率限制、API密钥验证、安全头设置
- 📊 安全事件监控 - 实时安全威胁检测和日志记录
⚡ 性能优化 (v1.1.0+)
- 🚀 元数据缓存系统 - 15-30% 性能提升
- 🏭 控制器单例管理 - 智能实例复用
- 🌳 Trie树路由匹配 - O(m) 复杂度的高效路由查找
- 📊 性能监控系统 - 实时性能指标收集
- 📝 结构化日志系统 - 安全、高性能的日志记录
- 🎯 智能缓存策略 - 分层缓存优化
📦 安装
npm install @studiogm/kara-core🚀 快速开始
1. 基础控制器
import 'reflect-metadata';
import {
Controller,
Get,
Post,
Put,
Delete,
Param,
Query,
Body,
Ctx
} from '@studiogm/kara-core';
import type { Context } from 'koa';
@Controller('/api/v1/users')
export class UserController {
@Get('/')
async getUsers(@Query('page') page: string = '1') {
return {
success: true,
data: [
{ id: '1', username: 'john_doe', email: '[email protected]' },
{ id: '2', username: 'jane_smith', email: '[email protected]' }
],
pagination: { page: parseInt(page), total: 2 }
};
}
@Get('/:id')
async getUser(@Param('id') id: string) {
return {
success: true,
data: { id, username: 'john_doe', email: '[email protected]' }
};
}
@Post('/')
async createUser(@Body() userData: any, @Ctx() ctx: Context) {
const newUser = {
id: Date.now().toString(),
...userData,
createdAt: new Date().toISOString()
};
ctx.status = 201;
return {
success: true,
data: newUser,
message: '用户创建成功'
};
}
@Put('/:id')
async updateUser(@Param('id') id: string, @Body() userData: any) {
return {
success: true,
data: { id, ...userData, updatedAt: new Date().toISOString() },
message: '用户更新成功'
};
}
@Delete('/:id')
async deleteUser(@Param('id') id: string) {
return {
success: true,
message: `用户 ${id} 删除成功`
};
}
}2. 应用级别装饰器(推荐)
import 'reflect-metadata';
import {
App,
Listen,
Cors,
BodyParser,
Use,
ErrorHandler,
createApplication
} from '@studiogm/kara-core';
import { UserController } from './controllers/UserController';
import type { Context } from 'koa';
@App([UserController]) // 注册控制器
@Listen(3000) // 监听端口
@Cors({ // 配置CORS
origin: ['http://localhost:3000', 'http://localhost:8080'],
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
headers: ['Content-Type', 'Authorization', 'X-Requested-With']
})
@BodyParser({ // 配置请求体解析
enableTypes: ['json', 'form'],
jsonLimit: '10mb',
formLimit: '10mb'
})
@Use( // 使用自定义中间件
// 请求计时中间件
async (ctx: Context, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
},
// API版本中间件
async (ctx: Context, next) => {
ctx.set('X-API-Version', '1.0.0');
await next();
}
)
@ErrorHandler( // 自定义错误处理
(error: any, ctx: Context) => {
console.error('应用错误:', error.message);
if (error.name === 'ValidationError') {
ctx.status = 400;
ctx.body = { success: false, error: '数据验证失败' };
} else if (error.status === 404) {
ctx.status = 404;
ctx.body = { success: false, error: '资源未找到' };
} else {
ctx.status = 500;
ctx.body = { success: false, error: '服务器内部错误' };
}
}
)
export class MyApplication {
onApplicationStart() {
console.log('🎉 应用程序启动完成!');
console.log('📍 服务地址: http://localhost:3000');
}
}
// 创建并启动应用程序
if (require.main === module) {
const app = createApplication(MyApplication);
// 可以获取原生Koa实例进行更多自定义
const koaApp = app.getKoaApp();
// 添加健康检查端点
koaApp.use(async (ctx, next) => {
if (ctx.path === '/health') {
ctx.body = {
status: 'ok',
timestamp: new Date().toISOString(),
uptime: process.uptime()
};
return;
}
await next();
});
}3. 传统方式(兼容)
import 'reflect-metadata';
import Koa from 'koa';
import { createRouter } from '@studiogm/kara-core';
import { UserController } from './controllers/UserController';
const app = new Koa();
const router = createRouter(UserController);
app.use(router.routes());
app.listen(3000);📚 API文档
装饰器
控制器装饰器
@Controller(prefix?)- 定义控制器类和路由前缀
路由装饰器
@Get(path)- GET请求路由@Post(path)- POST请求路由@Put(path)- PUT请求路由@Delete(path)- DELETE请求路由
参数装饰器
@Param(key)- 路径参数注入@Query(key)- 查询参数注入@Body()- 请求体注入@Ctx()- Koa上下文注入@Next()- Next函数注入
应用级别装饰器
@App(controllers)- 注册控制器到应用@Listen(port)- 配置应用监听端口@Cors(options)- 配置跨域资源共享@BodyParser(options)- 配置请求体解析中间件@Use(...middlewares)- 添加自定义中间件@ErrorHandler(handler)- 自定义错误处理逻辑
工具函数
createRouter(controller)- 创建路由器createApplication(AppClass)- 创建应用程序实例
🎯 使用场景
RESTful API
@Controller('/api/v1/posts')
export class PostController {
@Get('/')
async getPosts(@Query('page') page: string) { /* ... */ }
@Get('/:id')
async getPost(@Param('id') id: string) { /* ... */ }
@Post('/')
async createPost(@Body() postData: any) { /* ... */ }
@Put('/:id')
async updatePost(@Param('id') id: string, @Body() postData: any) { /* ... */ }
@Delete('/:id')
async deletePost(@Param('id') id: string) { /* ... */ }
}中间件集成
@Use(
// 认证中间件
async (ctx, next) => {
const token = ctx.headers.authorization;
if (!token) {
ctx.status = 401;
return;
}
await next();
},
// 日志中间件
async (ctx, next) => {
console.log(`${ctx.method} ${ctx.url}`);
await next();
}
)
export class SecureApplication {}🔧 配置选项
CORS配置
@Cors({
origin: ['http://localhost:3000'],
methods: ['GET', 'POST'],
headers: ['Content-Type', 'Authorization'],
credentials: true
})请求体解析配置
@BodyParser({
enableTypes: ['json', 'form', 'text'],
jsonLimit: '10mb',
formLimit: '10mb',
textLimit: '10mb'
})📝 示例项目
查看 example-usage/ 目录获取完整的使用示例。
cd example-usage
npm install
npm run dev # 开发模式
npm run build # 构建项目
npm run start # 启动服务
npm run test # 运行测试🤝 贡献
欢迎提交Issue和Pull Request!
📄 许可证
MIT License
