dp-koa-framework-core
v0.2.0
Published
DP-Koa framework core (v2 upgrade package)
Readme
dp-koa-framework-core
DP-Koa Framework 的核心库(Koa + 装饰器风格 Controller + 可插拔注解处理器 + 内建缓存/Swagger/Session 等能力)。
适合希望用“类 + 装饰器”方式组织 Koa API 的项目;同时支持“旧注解系统”和“新注解处理器系统(Processor)”两套执行链路,通过环境变量开关切换。
安装
npm i dp-koa-framework-core请求日志(默认行为)
bootstrap() 挂载的 loggingMiddleware 在核心包内只处理与「请求出错」相关的输出:
- HTTP 状态 ≥ 400:
security('HTTP_ERROR_RESPONSE', …)(4xx 为 medium,5xx 为 high) - 未捕获异常:
error('Request failed', …)后重新抛出,由后续错误中间件处理
每个请求仍会注入 ctx.logger 与 ctx.requestId,访问轨迹、慢请求、业务审计等请在业务项目自行 app.use 中间件或在 Controller/Service 中调用 ctx.logger / 全局 logger 记录。
businessLoggingMiddleware / databaseLoggingMiddleware 仍导出为空实现(兼容旧 import),默认不再在 bootstrap 中注册。
日志时间格式与控制台
- 控制台时间:
yyyy-MM-dd hh:mm:ss(精确到秒)。hh在 log4js 所用 date-format 中表示 24 小时,勿写HH。 .184含义:若你在文件或其它输出里仍看到 秒后面带.xxx,那是 毫秒(0–999),不是「小数秒」的另一种写法;结构化日志 JSON 里timestamp仍带.SSS便于排序与排查。- 控制台颜色:使用 pattern 的
%[…%]包裹前缀,按 日志级别 着色(与旧colored类似);勿用type: 'colored'自定义日期,该布局会忽略 pattern。 - 控制台级别过滤:默认只输出
info+;LOG_CONSOLE_LEVEL=debug透出全部;LOG_LEVEL可覆盖分类级别(见本节「请求日志(默认行为)」)。
快速上手(最小可运行示例)
import Koa from "koa";
import bodyParser from "koa-bodyparser";
import {
bindRouter,
router,
Get,
Query,
bootstrap,
logger,
} from "dp-koa-framework-core";
class HelloController {
@Get("/hello")
async hello(@Query() query: any) {
return { code: 0, data: { message: "hello", query } };
}
}
async function main() {
const app = new Koa();
app.use(bodyParser());
// 绑定路由(把装饰器声明的方法注册到 koa-router)
bindRouter("", HelloController);
app.use(router.routes()).use(router.allowedMethods());
// 也可以使用框架提供的 bootstrap(若你的项目使用框架的完整启动链路)
// await bootstrap(app);
const port = 3000;
app.listen(port, () => logger.info(`listening on :${port}`));
}
main();Controller 装饰器
路由方法
@Get(url?)/@Post(url?)/@Put(url?)/@Del(url?)/@All(url?)
参数注入
@Body():ctx.request.body@Query():ctx.query@Params():ctx.params@State()/@State('user'):ctx.state或ctx.state.user@Session()/@Session('uid'):ctx.session或ctx.session.uid@Headers()/@Headers('x-key'):ctx.request.headers或ctx.request.headers['x-key']@Cookie('name'):读取单个 cookie(默认signed: true,依赖app.keys)@Cookie():注入绑定当前请求的 cookie 读写句柄(get/set,默认signed: true;可在调用时传入signed: false覆盖)
示例:
import { Get, Query, Headers, Session, State, Cookie } from "dp-koa-framework-core";
class DemoController {
@Get("/demo")
async demo(
@Query() query: any,
@Headers("x-key") xKey: string,
@Session("uid") uid: string,
@State("user") user: any,
@Cookie("sid") sid: string,
@Cookie() cookies: { get: Function; set: Function }
) {
cookies.set("visited", "1", { httpOnly: true, maxAge: 7 * 24 * 60 * 60 * 1000 });
return { code: 0, data: { query, xKey, uid, user, sid } };
}
}DTO 校验规则(class-validator)
当你在参数装饰器里传入一个 DTO 类(构造函数)时,框架会在调用 controller 之前:
- 用传入的数据创建 DTO 实例(支持字段预处理
@Transform) - 执行
class-validator校验 - 校验失败时返回
400,并把校验错误写入ctx.body - 校验通过时,把 DTO 实例(而不是原始对象)作为入参传给 controller
适用的参数装饰器(常用):
@Body(Dto)/@Query(Dto)/@Params(Dto)/@Headers(Dto)/@State(Dto)/@Session(Dto)(不含@Cookie(Dto))
示例:
import { Get, Query, Transform } from "dp-koa-framework-core";
import { IsInt, IsOptional, IsString, Min } from "class-validator";
class ListDto {
@IsInt()
@Min(1)
@Transform((v) => Number(v))
page!: number;
@IsOptional()
@IsString()
keyword?: string;
}
class DemoDtoController {
@Get("/dto")
async list(@Query(ListDto) dto: ListDto) {
// dto.page 已被 Transform 成 number 且通过校验
return { code: 0, data: dto };
}
}响应控制(可选)
@ResponseCode(201):设置ctx.status@ResponseHeader('X-Name', 'value'):设置响应头@ControllerCache(cacheKeyFn, { ttl }):控制器方法结果缓存@ResponseValidator(...)/@ResponseValidateIf(...):响应数据校验
HTTP 重定向(SSO 常用)
框架支持 controller 声明式返回重定向响应,由路由层统一写入:
ctx.status = 302|303|307|308LocationheaderCache-Control: no-store
用法:
import { Get, redirect, Query } from "dp-koa-framework-core";
class SsoController {
@Get("/sso/login")
async login(@Query() query: any) {
const next = query?.next ? String(query.next) : "";
const url = `https://sso.example.com/login${next ? `?next=${encodeURIComponent(next)}` : ""}`;
return redirect(url, { status: 302 });
}
}说明:若返回
redirect(...),框架会优先处理重定向并短路;不会再走 JSON 响应校验/缓存等逻辑。
服务端模板(art-template)
在应用入口调用 initArtTemplate 配置是否启用、模板根目录等;Controller 中 return template('视图名', data),风格与 return redirect(...) 一致,由路由层渲染为 HTML,不必在 Controller 里直接操作 ctx。
import path from "path";
import { initArtTemplate, template, Get } from "dp-koa-framework-core";
// 入口(仅示例,路径按项目调整)
initArtTemplate({
enabled: true,
root: path.join(process.cwd(), "views"),
extname: ".html",
});import { Get, template } from "dp-koa-framework-core";
class PageController {
@Get("/page")
async page() {
return template("home/index", { title: "首页" });
}
}enabled: false:不加载 art-template;若仍return template(...),运行时会抛出明确错误。@ResponseValidator/@ResponseValidateIf:与redirect相同,template(...)短路,不会走针对 JSON 的响应 DTO 校验。@ControllerCache+template():支持;缓存的是渲染后的 HTML(内部带标记包装以便命中时恢复Content-Type)。cacheKeyFn必须随影响页面内容的入参(如query、params)变化;含用户态、AB 实验的页面慎用或把维度编入 key。
新/旧注解系统切换(USE_NEW_ANNOTATION_SYSTEM)
框架内部存在两套执行链路:
- 旧链路:传统参数注入 +
ctx.body = returnValue - 新链路:注解处理器系统(Processor)+
AnnotationExecutor执行
用环境变量切换:
# 1 启用新注解处理器系统;0 使用旧链路(默认)
USE_NEW_ANNOTATION_SYSTEM=1项目启动时也可以使用:
import { MigrationHelper } from "dp-koa-framework-core";
MigrationHelper.initializeNewSystem();数据库配置:db_mode(推荐)
推荐使用 db_mode 明确指定数据库模式:
# 1) SQLite 内存模式(每次启动重建)
db_mode=sqlite_memory
# 2) SQLite 文件持久化模式(重启保留数据)
db_mode=sqlite_file
db_sqlite_file=./data/dev.sqlite
# 3) PostgreSQL
db_mode=postgres
# 4) MySQL
db_mode=mysqlSQLite 行为说明:
db_mode=sqlite_memory:database=':memory:',dropSchema=truedb_mode=sqlite_file:必须设置db_sqlite_file,并使用dropSchema=false
建议把 SQLite 文件加入忽略规则(如 data/*.sqlite),避免误提交到仓库。
legacy 兼容(db_memory/db_type)
若未设置 db_mode,框架会按旧逻辑回退:
db_memory=1:使用 SQLite(若设置db_sqlite_file则文件模式,否则:memory:)\n-db_memory!=1:由db_type=mysql|postgres决定数据库类型
注解处理器(Processor)与企业级装饰器
框架提供可插拔的“注解处理器系统”,用于把日志、鉴权、限流、性能监控等横切能力以注解形式组合到 controller 方法上。
常用导出(示例,具体以版本为准):
Logging()/Permission()/RateLimit()等注解装饰器ProcessorManager:注册与管理处理器
导出入口一览
你可以从包入口直接使用以下能力(节选):
- 启动/服务:
bootstrap、App、getServer、closeServer - 路由:
router、bindRouter - 装饰器:
Get/Post/...、Body/Query/Params/Headers/State/Session - Swagger:
getSwaggerSpec、Api/ApiTags/ApiResponse/... - 缓存:
createCache、CacheType、getCacheStats - 重定向:
redirect - 服务端模板:
initArtTemplate、template
兼容性与约定
- Node.js:建议 18+
- 装饰器:需要 TypeScript 启用
experimentalDecorators - Headers key:HTTP header 在 Node/Koa 中通常是小写 key(如
x-key);请按你项目实际的 headers 形态取值
License
MIT(以仓库声明为准)
