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

koa-ts-core

v0.3.12

Published

A lightweight enterprise-grade backend framework based on Koa 3 and TypeScript.

Readme

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 等)的自动合并。

🚀 快速开始

安装

npm install koa-ts-core reflect-metadata
# 或
pnpm add koa-ts-core reflect-metadata

⚠️ 注意:必须在入口文件顶部引入 reflect-metadata,且 tsconfig.json 需开启 experimentalDecoratorsemitDecoratorMetadata

初始化

在入口文件 (如 src/main.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}`);
    console.log(`Swagger UI: http://localhost:${port}/swagger-ui`);
  });
}

bootstrap();

📚 API 参考

1. 路由装饰器 (Routing Decorators)

koa-ts-core 提供类级别和方法级别的路由定义。

@Router(method, path)

普通路由装饰器。

  • method: 'get' | 'post' | 'put' | 'delete' | 'patch' | 'all' (默认 'get')
  • path: 路由路径 (支持 path-to-regexp 语法,如 /:id)
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 才放行。

@AuthRouter("post", "/admin/update")
async update(ctx: Context) {
  // 只有鉴权通过才会执行这里
}

2. Swagger / OpenAPI 装饰器

完全支持 OpenAPI 3.0 标准元数据定义。

  • @ApiTags(tags: string[]): 定义 Controller 标签
  • @ApiOperation(summary, description): 接口摘要
  • @ApiParam(options): 定义 path 参数 (如 /:id)
  • @ApiQuery(options): 定义 query 参数
  • @ApiBody(options): 定义 request body
  • @ApiResponse(options): 定义响应结构
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 会自动合并这些文档配置,无需手写繁琐的装饰器。

3. 取用上下文 (Context Store)

无需在所有函数中透传 ctx

import { getCurrentContext } from "koa-ts-core";

// 在任意 Service 或 Utils 中
function doSomething() {
  const ctx = getCurrentContext();
  // 获取当前请求的 trackId
  const traceId = ctx.trackId;
}

4. 统一响应工具 (Response Helpers)

提供了一组工具函数来标准化 API 返回结构 { code, message, data, trackId }

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: "禁止访问" });

5. 异常处理 (BaseException)

推荐继承 BaseException 来抛出业务异常,通过全局错误中间件统一处理。

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" ... }

6. 参数校验 (Request Validation)

框架支持约定式参数校验。若未使用 @Validate 装饰器,会自动查找并执行符合命名规范的校验方法。

目录与命名约定 (Conventions):

  • Mapping Rule (目录映射): src/validate 目录结构必须与 src/controller 完全一致。
  • Naming Rule (文件命名): Validator 文件名必须与 Controller 文件名一致。
  • Method Binding (方法绑定): Validator 类中的静态方法 (static) 必须与 Controller 中的方法名一致 (例如: getUser -> getUser)。

示例:

// 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
  }
}

🛠 高级配置

阶段式中间件 (Phase Middleware)

koa-ts-core 将请求生命周期划分为多个阶段:

  1. AsyncContext (上下文初始化)
  2. TrackId (追踪ID生成)
  3. ErrorHandling (全局错误捕获)
  4. Logging (日志记录)
  5. Security (Cors等)
  6. BodyParsing (请求体解析)
  7. Auth (鉴权)
  8. Routing (路由执行)

您可以在 createKoaApp 时通过 phaseMiddlewares 选项,在任意阶段的前 (before)、后 (after) 或替换 (use) 该阶段。

import { MiddlewarePhase } from "koa-ts-core";

createKoaApp({
  phaseMiddlewares: {
    [MiddlewarePhase.Auth]: {
      before: [myCustomAuthCheckMiddleware] // 在内置 Auth 之前执行
    }
  }
})

环境变量

约定根目录下 env/ 文件夹,优先级配置:环境特定 > 通用

  • .common.env (所有环境通用的配置)
  • .{env}.env (特定环境配置,如 .development.env)
  • .{env}.env.local (可选:本地覆盖配置)

🔗 相关链接