koa-ts-core 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,11 +2,14 @@
2
2
 
3
3
  基于 **TypeScript + [Koa3](https://koajs.com/)** 的轻量服务端核心库,提供:
4
4
 
5
- - 约定式路由(装饰器)
6
- - 权限与参数校验约定
5
+ - 约定式路由(装饰器,基于 `@koa/router`)
6
+ - 权限与参数校验约定(控制器 + 校验器目录约定)
7
7
  - 全局错误处理与统一响应体
8
- - 环境变量加载
9
- - 日志(log4js)集成
8
+ - 环境变量加载(多环境合并)
9
+ - 日志集成(log4,基于 log4js
10
+ - AsyncLocalStorage 请求上下文获取
11
+ - 阶段式中间件管线与扩展(Phase Middleware)
12
+ - TrackId(RequestId)生成与透传
10
13
  - 接口文档生成基础能力(配合 `koa-ts-cli` 使用)
11
14
 
12
15
  > 推荐配合脚手架工具 [koa-ts-cli](https://www.npmjs.com/package/koa-typescript-cli) 使用。
@@ -19,52 +22,98 @@
19
22
  npm i koa-ts-core
20
23
  # 或
21
24
  yarn add koa-ts-core
25
+ # 或
26
+ pnpm add koa-ts-core
22
27
  ```
23
28
 
24
29
  ---
25
30
 
26
- ## 快速开始
31
+ ## 快速开始(推荐新 API)
27
32
 
28
- ### 初始化应用
33
+ ### 初始化应用(`createKoaApp`)
29
34
 
30
35
  在项目入口文件(如 `src/main.ts`)中:
31
36
 
32
37
  ```ts
33
38
  import Koa from "koa";
34
39
  import cors from "koa2-cors";
35
- import { initializeKoaApp, TLog4 } from "koa-ts-core";
40
+ import { createKoaApp } from "koa-ts-core";
36
41
 
37
42
  async function bootstrap() {
38
- const [app] = await initializeKoaApp({
39
- // 鉴权逻辑(配合 @AuthRouter 使用)
40
- authCheckCallback: async (ctx) => {
41
- // TODO: 你的权限判断
42
- return true;
43
+ const [app] = await createKoaApp({
44
+ // 自定义 koa 实例(可选,不传则内部创建)
45
+ koaInstance: new Koa(),
46
+
47
+ // 鉴权配置(配合 @AuthRouter 使用)
48
+ auth: {
49
+ handler: async (ctx) => {
50
+ // TODO: 你的权限判断逻辑
51
+ // return true / false 或直接抛异常
52
+ },
43
53
  },
44
54
 
45
- // CORS 中间件
46
- corsMiddleware: cors(),
47
-
48
- // 高优先级中间件(在内置中间件之前执行)
49
- registerHighPriorityMiddleware: (app: Koa) => {
50
- // app.use(yourMiddleware);
55
+ // 错误处理配置
56
+ error: {
57
+ // 自定义错误处理函数
58
+ handler: (error, ctx) => {
59
+ console.error("Global error:", error);
60
+ // 这里可以做统一日志、告警上报等
61
+ },
62
+ // 是否在响应中暴露堆栈(默认:非生产环境为 true,生产为 false)
63
+ // exposeStack: process.env.NODE_ENV !== "production",
51
64
  },
52
65
 
53
- // 全局错误回调
54
- catchErrorCallback: (error, ctx) => {
55
- console.error("Global error:", error);
66
+ // 日志配置
67
+ log: {
68
+ // log4:基础日志能力(log4js)
69
+ // false 或不传:不启用 log4
70
+ // true: 使用默认 log4 配置
71
+ // 函数:自定义 log4 配置
72
+ log4: true,
73
+
74
+ // 是否开启每次请求的运行时日志
75
+ runtimeLog: true,
56
76
  },
57
77
 
58
- // 请求生命周期 hook:request / response / error
59
- registerHook: (ctx, type) => {
60
- // your tracing / metrics logic
78
+ // Hook 配置:请求生命周期 request / response / error
79
+ hooks: {
80
+ register: (ctx, type) => {
81
+ // your tracing / metrics logic
82
+ // type: "request" | "response" | "error"
83
+ },
61
84
  },
62
85
 
63
- // 日志:true 为默认配置,函数为自定义配置
64
- log4: true as TLog4,
86
+ // CORS 中间件(例如 koa2-cors)
87
+ koa2Cors: cors(),
88
+
89
+ // TrackId(RequestId)配置
90
+ trackId: {
91
+ /**
92
+ * 生成 trackId 的函数:
93
+ * - 默认:优先从 header `x-request-id` 透传;没有就生成 uuid.v4()
94
+ * - 传入 false:禁用 trackId,不生成、不透传
95
+ */
96
+ // generator: false,
65
97
 
66
- // 是否开启运行时日志
67
- runtimeLog: true,
98
+ // 是否写回响应头(默认 true)
99
+ exposeHeader: true,
100
+
101
+ // header 名称(默认 "x-request-id")
102
+ headerName: "x-request-id",
103
+ },
104
+
105
+ /**
106
+ * 阶段式中间件扩展
107
+ * 你可以在 AsyncContext / ErrorHandling / Logging / Security / BodyParsing / Auth / Routing
108
+ * 每一个阶段前/后插入自定义中间件
109
+ */
110
+ // phaseMiddlewares: {
111
+ // [MiddlewarePhase.Logging]: {
112
+ // before: [traceMiddleware],
113
+ // use: [metricsMiddleware],
114
+ // after: [yourCustomMiddleware],
115
+ // },
116
+ // },
68
117
  });
69
118
 
70
119
  app.listen(process.env.APP_PORT ?? 3000, () => {
@@ -79,59 +128,203 @@ bootstrap();
79
128
 
80
129
  ---
81
130
 
82
- ## 初始化配置说明
131
+ ## 初始化配置说明(`CreateKoaOptions`)
132
+
133
+ `createKoaApp(options?: Partial<CreateKoaOptions>)` 支持以下配置块:
83
134
 
84
- `initializeKoaApp(options?: TInitOptions)` 支持以下字段:
135
+ ### 基础
85
136
 
86
137
  - **koaInstance?: Koa**
87
- 自定义 Koa 实例,不传则自动创建。
138
+ 自定义 Koa 实例,不传则内部 `new Koa()`。
139
+
140
+ - **koa2Cors?: Koa.Middleware**
141
+ CORS 中间件,一般为 `koa2-cors()`。
142
+
143
+ - **phaseMiddlewares?: PhaseMiddlewareMap**
144
+ 阶段式中间件扩展,按阶段插入自定义中间件,详见「中间件链路与阶段扩展」。
145
+
146
+ ---
147
+
148
+ ### 鉴权配置:`auth?: AuthConfig`
149
+
150
+ ```ts
151
+ interface AuthConfig {
152
+ handler?: (ctx: Koa.Context) => Promise<boolean> | boolean;
153
+ }
154
+ ```
155
+
156
+ - **handler**
157
+ 鉴权回调,配合 `@AuthRouter` 使用。
158
+ 你可以在这里检查登录态、角色、权限,抛错或返回布尔值。
88
159
 
89
- - **corsMiddleware?: Koa.Middleware**
90
- CORS 中间件。
160
+ ---
91
161
 
92
- - **authCheckCallback?: (ctx: Koa.Context) => boolean | Promise<boolean>**
93
- 鉴权回调,配合 `@AuthRouter` 使用。
162
+ ### 错误处理配置:`error?: ErrorConfig`
94
163
 
95
- - **catchErrorCallback?: (error: Error, ctx?: Koa.Context) => void**
96
- 全局错误回调,用于统一处理未捕获错误。
164
+ ```ts
165
+ interface ErrorConfig {
166
+ handler?: (error: unknown, ctx: Koa.Context) => void | Promise<void>;
167
+ exposeStack?: boolean; // 默认:非生产环境 true,生产 false
168
+ }
169
+ ```
97
170
 
98
- - **registerHighPriorityMiddleware?: (app: Koa) => void**
99
- 高优先级中间件注册函数,在框架内置中间件之前执行。
171
+ - **handler**
172
+ 自定义错误回调,用于统一处理未捕获错误(日志、告警等)。
100
173
 
101
- - **registerHook?: (ctx: Koa.Context, type: "request" | "response" | "error") => void**
102
- 请求生命周期 hook。
174
+ - **exposeStack**
175
+ 是否在响应中暴露错误堆栈信息,一般开发环境开启,生产关闭。
103
176
 
104
- - **log4?: TLog4**
105
- 是否挂载 log4js 及配置方式:
177
+ ---
178
+
179
+ ### 日志配置:`log?: LogConfig`
180
+
181
+ ```ts
182
+ type TLog4 =
183
+ | boolean
184
+ | ((instance: import("log4js").Log4js) => import("log4js").Log4js);
185
+
186
+ interface LogConfig {
187
+ log4?: TLog4;
188
+ runtimeLog?: boolean;
189
+ }
190
+ ```
191
+
192
+ - **log4**
106
193
 
107
194
  - `false` / 不传:不启用 log4
108
195
  - `true`:使用默认 log4js 配置
109
- - `(instance: Log4js) => Log4js`:自定义配置
196
+ - `(instance) => instance`: 自定义配置 log4js 实例
110
197
 
111
- - **runtimeLog?: boolean**
112
- 是否挂载运行时日志能力到 `ctx.runtimeLog`。
198
+ - **runtimeLog**
199
+ 是否开启每次请求的运行时日志(挂载到 `ctx.runtimeLog`,配合内置 `loggerMiddleware` 使用)。
113
200
 
114
201
  ---
115
202
 
116
- ## 获取当前请求上下文
203
+ ### Hook 配置:`hooks?: HookConfig`
204
+
205
+ ```ts
206
+ type HookType = "request" | "response" | "error";
207
+
208
+ interface HookConfig {
209
+ register?: (ctx: Koa.Context, type: HookType) => void;
210
+ }
211
+ ```
117
212
 
118
- 框架通过 `AsyncLocalStorage` 在异步链路中保存 Koa 的 `Context`,从而在**无需显式传递 `ctx` 参数**的情况下,也能获取当前请求的上下文。
213
+ - **register**
214
+ 请求生命周期 hook,在请求开始/结束/异常时被调用,可用于埋点、监控。
119
215
 
120
- ### getCurrentContext()
216
+ ---
217
+
218
+ ### TrackId 配置:`trackId?: TrackIdConfig`
121
219
 
122
220
  ```ts
221
+ export type TrackIdGenerator =
222
+ | false
223
+ | ((
224
+ ctx: Koa.Context
225
+ ) => string | null | undefined | Promise<string | null | undefined>);
226
+
227
+ export interface TrackIdConfig {
228
+ generator?: TrackIdGenerator; // 默认:header 透传或 uuid.v4
229
+ exposeHeader?: boolean; // 默认 true
230
+ headerName?: string; // 默认 "x-request-id"
231
+ }
232
+ ```
233
+
234
+ - **generator**
235
+
236
+ - 不配置:默认使用 `x-request-id` header 或生成 `uuid.v4()`
237
+ - 设置为 `false`:禁用 trackId,不生成、不透传
238
+ - 自定义函数:可按业务需要生成(或透传) trackId
239
+
240
+ - **exposeHeader**
241
+ 是否将 trackId 写回响应头(默认 `true`)。
242
+
243
+ - **headerName**
244
+ 请求/响应中使用的 header 名称(默认 `"x-request-id"`)。
245
+
246
+ ---
247
+
248
+ ## 中间件链路与阶段扩展
249
+
250
+ 框架将中间件链路拆分为多个“阶段”(`MiddlewarePhase`),内部按顺序执行,用户可在每个阶段前/后扩展中间件。
251
+
252
+ 默认阶段顺序:
253
+
254
+ 1. **AsyncContext**
255
+ AsyncLocalStorage 上下文中间件,保证在异步链路中可以获取当前请求的 `ctx`。
256
+
257
+ 2. **TrackId**
258
+ TrackId 生成与透传中间件(根据 `trackId` 配置生成、挂载 `ctx.trackId`,并写入响应头)。
259
+
260
+ 3. **ErrorHandling**
261
+ 全局错误处理,中间件会捕获异常并调用 `error.handler`。
262
+
263
+ 4. **Logging**
264
+ 请求日志与耗时统计(结合 `log4` 和 `runtimeLog`)。
265
+
266
+ 5. **Security**
267
+ CORS / 安全相关中间件(例如 `koa2-cors`)。
268
+
269
+ 6. **BodyParsing**
270
+ `koa-bodyparser` + 请求参数挂载(`requestParamsMiddleware`)。
271
+
272
+ 7. **Auth**
273
+ 鉴权中间件,配合 `auth.handler` 与 `@AuthRouter`。
274
+
275
+ 8. **Routing**
276
+ 约定式路由分发(`@Router` / `@AuthRouter` + `@koa/router`)。
277
+
278
+ ### 阶段扩展:PhaseMiddlewareMap
279
+
280
+ 你可以在任意阶段插入自定义中间件:
281
+
282
+ ```ts
283
+ import { MiddlewarePhase } from "koa-ts-core/types/core";
284
+
285
+ createKoaApp({
286
+ phaseMiddlewares: {
287
+ [MiddlewarePhase.Logging]: {
288
+ before: [
289
+ async (ctx, next) => {
290
+ // 在内置 Logging 中间件之前
291
+ await next();
292
+ },
293
+ ],
294
+ use: [
295
+ async (ctx, next) => {
296
+ // 与内置 Logging 同阶段,追加在后面
297
+ await next();
298
+ },
299
+ ],
300
+ after: [
301
+ async (ctx, next) => {
302
+ // 整个 Logging 阶段之后
303
+ await next();
304
+ },
305
+ ],
306
+ },
307
+ },
308
+ });
309
+ ```
310
+
311
+ 每个阶段都支持 `before` / `use` / `after` 三种插入点。
312
+
313
+ ---
314
+
315
+ ## 获取当前请求上下文(AsyncLocalStorage)
316
+
317
+ 框架通过 `AsyncLocalStorage` 在异步链路中保存 `Koa.Context`,无需层层传递 `ctx`,即可在任意业务代码中获取当前请求上下文。
318
+
319
+ `context_middleware` 已在 `AsyncContext` 阶段自动挂载,你只需要在业务侧使用工具函数:
320
+
321
+ ```ts
322
+ // 示例:getCurrentContext.ts(具体导出以实际实现为准)
123
323
  import { AsyncLocalStorage } from "async_hooks";
124
324
  import type { Context } from "koa";
125
325
 
126
- // 全局上下文存储
127
326
  export const contextStore = new AsyncLocalStorage<Context>();
128
327
 
129
- /**
130
- * 获取当前请求的 Koa Context
131
- *
132
- * 仅在被 AsyncLocalStorage 包裹的异步调用链中生效。
133
- * 若当前不存在上下文,将抛出异常。
134
- */
135
328
  export const getCurrentContext = (): Context => {
136
329
  const context = contextStore.getStore();
137
330
  if (!context) {
@@ -141,19 +334,17 @@ export const getCurrentContext = (): Context => {
141
334
  };
142
335
  ```
143
336
 
144
- ---
145
-
146
- ## 中间件链路
337
+ 之后在任意位置:
147
338
 
148
- 内置中间件按以下顺序执行:
339
+ ```ts
340
+ import { getCurrentContext } from "koa-ts-core";
149
341
 
150
- 1. AsyncLocalStorage 上下文中间件
151
- 2. 全局错误处理
152
- 3. 请求日志 / 响应时间统计
153
- 4. CORS / 安全相关中间件
154
- 5. Body 解析
155
- 6. 鉴权(`authCheckCallback` + `@AuthRouter`)
156
- 7. 约定式路由分发
342
+ function doSomething() {
343
+ const ctx = getCurrentContext();
344
+ const trackId = (ctx as any).trackId;
345
+ ctx.log4?.info({ trackId }, "doSomething called");
346
+ }
347
+ ```
157
348
 
158
349
  ---
159
350
 
@@ -210,7 +401,7 @@ export default User;
210
401
 
211
402
  ### REST 风格简写
212
403
 
213
- 在不指定 method/path 时,`@Router` 会根据方法名进行推断:
404
+ 在不指定 method/path 时,`@Router` 会根据方法名推断:
214
405
 
215
406
  ```ts
216
407
  import Koa from "koa";
@@ -269,7 +460,7 @@ src
269
460
  └── api/v1/user.ts # 参数校验器
270
461
  ```
271
462
 
272
- 控制器中有方法 `userInfo` 时,对应的校验器为:
463
+ 示例:
273
464
 
274
465
  ```ts
275
466
  // src/validate/api/v1/user.ts
@@ -311,14 +502,6 @@ unSuccessRsp({ code, message, data });
311
502
  errorRsp(400, { message: "Bad Request" });
312
503
  ```
313
504
 
314
- 类型签名(简化):
315
-
316
- ```ts
317
- export declare const successRsp: (options?: Options) => void;
318
- export declare const unSuccessRsp: (options?: Options) => void;
319
- export declare const errorRsp: (statusCode: number, options?: Options) => void;
320
- ```
321
-
322
505
  ---
323
506
 
324
507
  ## 异常处理
@@ -340,7 +523,7 @@ export class CustomException extends BaseException {
340
523
  throw new CustomException("自定义异常");
341
524
  ```
342
525
 
343
- 所有异常会被内置错误处理中间件捕获,并结合 `catchErrorCallback` 输出日志或自定义处理。
526
+ 所有异常会被内置错误处理中间件捕获,并结合 `error.handler` 输出日志或自定义处理。
344
527
 
345
528
  ---
346
529
 
@@ -367,65 +550,15 @@ env
367
550
 
368
551
  ## 文档生成(配合 koa-ts-cli)
369
552
 
370
- `koa-ts-core` 提供路由元信息,配合 `koa-ts-cli` 的 `koa-ts-cli doc` 命令,可以根据 `src/controller` 自动生成 `doc` 目录下的接口配置文件,并在运行时通过 `/doc` 路由查看渲染后的接口文档。
553
+ `koa-ts-core` 提供路由元信息,配合 `koa-ts-cli` 的 `koa-ts-cli doc` 命令,可以根据 `src/controller` 自动生成接口配置,并在运行时通过 `/doc` 路由查看渲染后的接口文档(仅开发环境或 `DOC=true` 时启用)。
371
554
 
372
- 具体 CLI 使用方式见:[koa-ts-cli](https://www.npmjs.com/package/koa-typescript-cli)(或对应仓库)。
555
+ 详细 CLI 使用方式参考:[koa-ts-cli](https://www.npmjs.com/package/koa-typescript-cli)
373
556
 
374
557
  ---
375
558
 
376
- ## 日志:log4js 集成
377
-
378
- 配置项类型:
379
-
380
- ```ts
381
- type TLog4 = boolean | ((instance: Log4js) => Log4js);
382
- ```
383
-
384
- - 传入 `false` 或不传:不启用 log4
385
- - 传入 `true`:使用默认 log4 配置
386
- - 传入函数:自定义 log4 配置
387
-
388
- 默认配置示例(`log4: true`):
389
-
390
- ```js
391
- log4js.configure({
392
- appenders: {
393
- console: { type: "console" },
394
- file: {
395
- type: "dateFile",
396
- filename: "logs/app.log",
397
- pattern: ".yyyy-MM-dd",
398
- compress: true,
399
- numBackups: 7,
400
- alwaysIncludePattern: true,
401
- },
402
- },
403
- categories: {
404
- default: { appenders: ["console", "file"], level: "info" },
405
- },
406
- });
407
- ```
559
+ ## Context 扩展(部分示意)
408
560
 
409
- 自定义示例:
410
-
411
- ```ts
412
- initializeKoaApp({
413
- log4: (instance) => {
414
- return instance.configure({
415
- appenders: { console: { type: "console" } },
416
- categories: {
417
- default: { appenders: ["console"], level: "debug" },
418
- },
419
- });
420
- },
421
- });
422
- ```
423
-
424
- ---
425
-
426
- ## Context 扩展
427
-
428
- `koa-ts-core` 对 `Koa.Context` 做了类型拓展:
561
+ 框架对 `Koa.Context` 做了类型拓展,你可以在业务代码中使用这些字段:
429
562
 
430
563
  ```ts
431
564
  declare module "koa" {
@@ -446,6 +579,9 @@ declare module "koa" {
446
579
  post: Record<string, any>;
447
580
  };
448
581
 
582
+ // trackId(请求 ID)
583
+ trackId?: string;
584
+
449
585
  // 业务扩展字段
450
586
  extra: {
451
587
  get: Record<string, any>;
@@ -455,8 +591,6 @@ declare module "koa" {
455
591
  }
456
592
  ```
457
593
 
458
- ---
459
-
460
594
  ## 相关项目
461
595
 
462
596
  - [koa-ts-cli](https://www.npmjs.com/package/koa-typescript-cli):基于 `koa-ts-core` 的脚手架 CLI 工具,支持项目创建、开发、生成文档、自动生成控制器与校验器等。
package/dist/global.d.ts CHANGED
@@ -2,6 +2,8 @@ import "koa";
2
2
 
3
3
  declare module "koa" {
4
4
  interface DefaultContext {
5
+ // trackId
6
+ trackId?: string;
5
7
  // log4js
6
8
  log4?: import("log4js").Log4js;
7
9
  // hook