npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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 状态 ≥ 400security('HTTP_ERROR_RESPONSE', …)(4xx 为 medium,5xx 为 high)
  • 未捕获异常error('Request failed', …) 后重新抛出,由后续错误中间件处理

每个请求仍会注入 ctx.loggerctx.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.statectx.state.user
  • @Session() / @Session('uid')ctx.sessionctx.session.uid
  • @Headers() / @Headers('x-key')ctx.request.headersctx.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|308
  • Location header
  • Cache-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 必须随影响页面内容的入参(如 queryparams)变化;含用户态、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=mysql

SQLite 行为说明:

  • db_mode=sqlite_memorydatabase=':memory:'dropSchema=true
  • db_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:注册与管理处理器

导出入口一览

你可以从包入口直接使用以下能力(节选):

  • 启动/服务:bootstrapAppgetServercloseServer
  • 路由:routerbindRouter
  • 装饰器:Get/Post/...Body/Query/Params/Headers/State/Session
  • Swagger:getSwaggerSpecApi/ApiTags/ApiResponse/...
  • 缓存:createCacheCacheTypegetCacheStats
  • 重定向:redirect
  • 服务端模板:initArtTemplatetemplate

兼容性与约定

  • Node.js:建议 18+
  • 装饰器:需要 TypeScript 启用 experimentalDecorators
  • Headers key:HTTP header 在 Node/Koa 中通常是小写 key(如 x-key);请按你项目实际的 headers 形态取值

License

MIT(以仓库声明为准)