A lightweight enterprise-grade backend framework based on Koa 3 and TypeScript.
npm install koa-ts-core基于 TypeScript + Koa3 的轻量级企业级服务端核心框架。
它提供了一套完整的开发约定与核心能力封装,包括装饰器路由、自动文档生成、链路追踪、全局异常处理等,旨在提升 Koa 项目的开发规范与效率。
> 推荐配合脚手架工具 koa-ts-cli 使用最佳。
- 装饰器路由: 基于 @koa/router 封装,支持 @Router, @AuthRouter,风格类似 NestJS/Spring Boot。
- Swagger/OpenAPI 自动生成: 支持“零配置”扫描模式(配合 CLI)和“装饰器”定义模式。自动识别 Path/Query/Header/Body 参数。
- 全链路追踪 (Trace/Request ID): 基于 AsyncLocalStorage,内置 RequestId 生成与透传,支持全链路日志串联。
- 全局异常处理: 统一捕获异常,规范化错误响应。
- 统一响应体: 提供 successRsp, errorRsp 等工具函数,统一 API 返回格式。
- 阶段式中间件 (Phase Middleware): 独创的生命周期阶段管理,允许在 AsyncContext、Auth、Routing 等任意阶段前后注入中间件。
- 环境配置: 自动加载 env/ 目录下的配置文件,支持通用配置(.common.env)与环境特定配置(.development.env 等)的自动合并。
---
``bash`
npm install koa-ts-core reflect-metadata或
pnpm add koa-ts-core reflect-metadata
> ⚠️ 注意:必须在入口文件顶部引入 reflect-metadata,且 tsconfig.json 需开启 experimentalDecorators 和 emitDecoratorMetadata。
在入口文件 (如 src/main.ts) 中初始化应用:
`ts
import "reflect-metadata"; // 必须第一行引入
import { createKoaApp } from "koa-ts-core";
import Koa from "koa";
async function bootstrap() {
const [app] = await createKoaApp({
// 基础配置
koaInstance: new Koa(), // 可选:传入自定义 Koa 实例
// Swagger 文档配置
swagger: {
enabled: true,
path: "/swagger-ui",
title: "My API Service",
version: "1.0.0",
// 安全配置 (如 Bearer JWT)
securitySchemes: {
BearerAuth: {
type: "http",
scheme: "bearer",
bearerFormat: "JWT"
}
},
security: [{ BearerAuth: [] }] // 全局启用
},
// 错误处理
error: {
exposeStack: process.env.NODE_ENV === "development", // 开发环境暴露堆栈
handler: (err, ctx) => {
// 自定义错误上报逻辑 (如 Sentry)
console.error("Global Error Caught:", err);
}
},
// 全局鉴权回调 (配合 @AuthRouter)
auth: {
handler: async (ctx) => {
const token = ctx.header.authorization;
if (!token) throw new Error("Unauthorized");
// return true 表示通过
return true;
}
}
});
const port = process.env.APP_PORT || 3000;
app.listen(port, () => {
console.log(Server running at http://localhost:${port});Swagger UI: http://localhost:${port}/swagger-ui
console.log();
});
}
bootstrap();
`
---
koa-ts-core 提供类级别和方法级别的路由定义。
#### @Router(method, path)method
普通路由装饰器。
- : 'get' | 'post' | 'put' | 'delete' | 'patch' | 'all' (默认 'get')path
- : 路由路径 (支持 path-to-regexp 语法,如 /:id)
`ts
import { Router, Context } from "koa-ts-core";
class UserController {
// GET /user/:id
@Router("get", "/user/:id")
async getUser(ctx: Context) {
const { id } = ctx.params;
ctx.body = { id };
}
// 简写:不传参数默认 method='get', path='/方法名'
// GET /list
@Router()
async list(ctx: Context) { ... }
}
`
#### @AuthRouter(method, path)createKoaApp
鉴权路由装饰器。
执行前会先调用 中配置的 auth.handler,只有返回 true 才放行。
`ts`
@AuthRouter("post", "/admin/update")
async update(ctx: Context) {
// 只有鉴权通过才会执行这里
}
完全支持 OpenAPI 3.0 标准元数据定义。
- @ApiTags(tags: string[]): 定义 Controller 标签@ApiOperation(summary, description)
- : 接口摘要@ApiParam(options)
- : 定义 path 参数 (如 /:id)@ApiQuery(options)
- : 定义 query 参数@ApiBody(options)
- : 定义 request body@ApiResponse(options)
- : 定义响应结构
`ts
import { ApiTags, ApiOperation, ApiParam, ApiQuery, Router } from "koa-ts-core";
@ApiTags(["Order"])
class OrderController {
@Router("get", "/order/:orderId")
@ApiOperation("获取订单详情")
@ApiParam({ name: "orderId", description: "订单ID", example: "123" })
@ApiQuery({ name: "detail", required: false, description: "是否返回详情" })
async getOrder(ctx: Context) { ... }
}
`
> 💡 自动扫描模式:如果您使用 koa-ts-cli doc 生成了 doc/ 目录,swagger_collector 会自动合并这些文档配置,无需手写繁琐的装饰器。
无需在所有函数中透传 ctx。
`ts
import { getCurrentContext } from "koa-ts-core";
// 在任意 Service 或 Utils 中
function doSomething() {
const ctx = getCurrentContext();
// 获取当前请求的 trackId
const traceId = ctx.trackId;
}
`
提供了一组工具函数来标准化 API 返回结构 { code, message, data, trackId }。
`ts
import { successRsp, errorRsp, unSuccessRsp } from "koa-ts-core";
// 成功:HTTP 200, code=0
successRsp({ data: { id: 1 } });
// -> { code: 0, message: "success", data: { id: 1 }, trackId: "..." }
// 业务失败:HTTP 200, code!=0
unSuccessRsp({ code: 1001, message: "库存不足" });
// 异常:HTTP 400/500...
errorRsp(403, { message: "禁止访问" });
`
推荐继承 BaseException 来抛出业务异常,通过全局错误中间件统一处理。
`ts
import { BaseException } from "koa-ts-core";
export class UserNotFoundException extends BaseException {
constructor() {
super("User not found");
this.code = 404001;
}
}
// 在业务中:
throw new UserNotFoundException();
// 响应: HTTP 500 (默认), body: { code: 404001, message: "User not found" ... }
`
框架支持约定式参数校验。若未使用 @Validate 装饰器,会自动查找并执行符合命名规范的校验方法。
目录与命名约定 (Conventions):
- Mapping Rule (目录映射): src/validate 目录结构必须与 src/controller 完全一致。static
- Naming Rule (文件命名): Validator 文件名必须与 Controller 文件名一致。
- Method Binding (方法绑定): Validator 类中的静态方法 () 必须与 Controller 中的方法名一致 (例如: getUser -> getUser)。
示例:
`ts
// src/controller/api/user.ts
export default class UserController {
@Router('get', '/:id')
async getUser(ctx: Context) { ... }
}
// src/validate/api/user.ts
export default class UserValidator {
// 自动绑定到 UserController.getUser
static async getUser(ctx: Context) {
// 校验逻辑... 校验通过后的数据可存入 ctx.validated
}
}
`
---
koa-ts-core 将请求生命周期划分为多个阶段:AsyncContext
1. (上下文初始化)TrackId
2. (追踪ID生成)ErrorHandling
3. (全局错误捕获)Logging
4. (日志记录)Security
5. (Cors等)BodyParsing
6. (请求体解析)Auth
7. (鉴权)Routing
8. (路由执行)
您可以在 createKoaApp 时通过 phaseMiddlewares 选项,在任意阶段的前 (before)、后 (after) 或替换 (use) 该阶段。
`ts
import { MiddlewarePhase } from "koa-ts-core";
createKoaApp({
phaseMiddlewares: {
[MiddlewarePhase.Auth]: {
before: [myCustomAuthCheckMiddleware] // 在内置 Auth 之前执行
}
}
})
`
---
约定根目录下 env/ 文件夹,优先级配置:环境特定 > 通用。.common.env
- (所有环境通用的配置).{env}.env
- (特定环境配置,如 .development.env).{env}.env.local` (可选:本地覆盖配置)
-
---