koa-ts-core 0.1.0-dev.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
@@ -1,12 +1,15 @@
1
1
  # koa-ts-core
2
2
 
3
- 基于 **TypeScript + Koa** 的轻量服务端核心库,提供:
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,
97
+
98
+ // 是否写回响应头(默认 true)
99
+ exposeHeader: true,
65
100
 
66
- // 是否开启运行时日志
67
- runtimeLog: true,
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,51 +128,223 @@ bootstrap();
79
128
 
80
129
  ---
81
130
 
82
- ## 初始化配置说明
131
+ ## 初始化配置说明(`CreateKoaOptions`)
83
132
 
84
- `initializeKoaApp(options?: TInitOptions)` 支持以下字段:
133
+ `createKoaApp(options?: Partial<CreateKoaOptions>)` 支持以下配置块:
134
+
135
+ ### 基础
85
136
 
86
137
  - **koaInstance?: Koa**
87
- 自定义 Koa 实例,不传则自动创建。
138
+ 自定义 Koa 实例,不传则内部 `new Koa()`。
88
139
 
89
- - **corsMiddleware?: Koa.Middleware**
90
- CORS 中间件。
140
+ - **koa2Cors?: Koa.Middleware**
141
+ CORS 中间件,一般为 `koa2-cors()`。
91
142
 
92
- - **authCheckCallback?: (ctx: Koa.Context) => boolean | Promise<boolean>**
93
- 鉴权回调,配合 `@AuthRouter` 使用。
143
+ - **phaseMiddlewares?: PhaseMiddlewareMap**
144
+ 阶段式中间件扩展,按阶段插入自定义中间件,详见「中间件链路与阶段扩展」。
94
145
 
95
- - **catchErrorCallback?: (error: Error, ctx?: Koa.Context) => void**
96
- 全局错误回调,用于统一处理未捕获错误。
146
+ ---
97
147
 
98
- - **registerHighPriorityMiddleware?: (app: Koa) => void**
99
- 高优先级中间件注册函数,在框架内置中间件之前执行。
148
+ ### 鉴权配置:`auth?: AuthConfig`
100
149
 
101
- - **registerHook?: (ctx: Koa.Context, type: "request" | "response" | "error") => void**
102
- 请求生命周期 hook。
150
+ ```ts
151
+ interface AuthConfig {
152
+ handler?: (ctx: Koa.Context) => Promise<boolean> | boolean;
153
+ }
154
+ ```
103
155
 
104
- - **log4?: TLog4**
105
- 是否挂载 log4js 及配置方式:
156
+ - **handler**
157
+ 鉴权回调,配合 `@AuthRouter` 使用。
158
+ 你可以在这里检查登录态、角色、权限,抛错或返回布尔值。
159
+
160
+ ---
161
+
162
+ ### 错误处理配置:`error?: ErrorConfig`
163
+
164
+ ```ts
165
+ interface ErrorConfig {
166
+ handler?: (error: unknown, ctx: Koa.Context) => void | Promise<void>;
167
+ exposeStack?: boolean; // 默认:非生产环境 true,生产 false
168
+ }
169
+ ```
170
+
171
+ - **handler**
172
+ 自定义错误回调,用于统一处理未捕获错误(日志、告警等)。
173
+
174
+ - **exposeStack**
175
+ 是否在响应中暴露错误堆栈信息,一般开发环境开启,生产关闭。
176
+
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 实例
197
+
198
+ - **runtimeLog**
199
+ 是否开启每次请求的运行时日志(挂载到 `ctx.runtimeLog`,配合内置 `loggerMiddleware` 使用)。
200
+
201
+ ---
202
+
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
+ ```
212
+
213
+ - **register**
214
+ 请求生命周期 hook,在请求开始/结束/异常时被调用,可用于埋点、监控。
215
+
216
+ ---
217
+
218
+ ### TrackId 配置:`trackId?: TrackIdConfig`
219
+
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
+ ## 中间件链路与阶段扩展
110
249
 
111
- - **runtimeLog?: boolean**
112
- 是否挂载运行时日志能力到 `ctx.runtimeLog`。
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` 三种插入点。
113
312
 
114
313
  ---
115
314
 
116
- ## 中间件链路
315
+ ## 获取当前请求上下文(AsyncLocalStorage)
316
+
317
+ 框架通过 `AsyncLocalStorage` 在异步链路中保存 `Koa.Context`,无需层层传递 `ctx`,即可在任意业务代码中获取当前请求上下文。
318
+
319
+ `context_middleware` 已在 `AsyncContext` 阶段自动挂载,你只需要在业务侧使用工具函数:
320
+
321
+ ```ts
322
+ // 示例:getCurrentContext.ts(具体导出以实际实现为准)
323
+ import { AsyncLocalStorage } from "async_hooks";
324
+ import type { Context } from "koa";
325
+
326
+ export const contextStore = new AsyncLocalStorage<Context>();
117
327
 
118
- 内置中间件按以下顺序执行:
328
+ export const getCurrentContext = (): Context => {
329
+ const context = contextStore.getStore();
330
+ if (!context) {
331
+ throw new Error("context is not exist");
332
+ }
333
+ return context;
334
+ };
335
+ ```
119
336
 
120
- 1. AsyncLocalStorage 上下文中间件
121
- 2. 全局错误处理
122
- 3. 请求日志 / 响应时间统计
123
- 4. CORS / 安全相关中间件
124
- 5. Body 解析
125
- 6. 鉴权(`authCheckCallback` + `@AuthRouter`)
126
- 7. 约定式路由分发
337
+ 之后在任意位置:
338
+
339
+ ```ts
340
+ import { getCurrentContext } from "koa-ts-core";
341
+
342
+ function doSomething() {
343
+ const ctx = getCurrentContext();
344
+ const trackId = (ctx as any).trackId;
345
+ ctx.log4?.info({ trackId }, "doSomething called");
346
+ }
347
+ ```
127
348
 
128
349
  ---
129
350
 
@@ -180,7 +401,7 @@ export default User;
180
401
 
181
402
  ### REST 风格简写
182
403
 
183
- 在不指定 method/path 时,`@Router` 会根据方法名进行推断:
404
+ 在不指定 method/path 时,`@Router` 会根据方法名推断:
184
405
 
185
406
  ```ts
186
407
  import Koa from "koa";
@@ -239,7 +460,7 @@ src
239
460
  └── api/v1/user.ts # 参数校验器
240
461
  ```
241
462
 
242
- 控制器中有方法 `userInfo` 时,对应的校验器为:
463
+ 示例:
243
464
 
244
465
  ```ts
245
466
  // src/validate/api/v1/user.ts
@@ -281,14 +502,6 @@ unSuccessRsp({ code, message, data });
281
502
  errorRsp(400, { message: "Bad Request" });
282
503
  ```
283
504
 
284
- 类型签名(简化):
285
-
286
- ```ts
287
- export declare const successRsp: (options?: Options) => void;
288
- export declare const unSuccessRsp: (options?: Options) => void;
289
- export declare const errorRsp: (statusCode: number, options?: Options) => void;
290
- ```
291
-
292
505
  ---
293
506
 
294
507
  ## 异常处理
@@ -310,7 +523,7 @@ export class CustomException extends BaseException {
310
523
  throw new CustomException("自定义异常");
311
524
  ```
312
525
 
313
- 所有异常会被内置错误处理中间件捕获,并结合 `catchErrorCallback` 输出日志或自定义处理。
526
+ 所有异常会被内置错误处理中间件捕获,并结合 `error.handler` 输出日志或自定义处理。
314
527
 
315
528
  ---
316
529
 
@@ -337,65 +550,15 @@ env
337
550
 
338
551
  ## 文档生成(配合 koa-ts-cli)
339
552
 
340
- `koa-ts-core` 提供路由元信息,配合 `koa-ts-cli` 的 `koa-ts-cli doc` 命令,可以根据 `src/controller` 自动生成 `doc` 目录下的接口配置文件,并在运行时通过 `/doc` 路由查看渲染后的接口文档。
341
-
342
- 具体 CLI 使用方式见:[koa-ts-cli](https://www.npmjs.com/package/koa-typescript-cli)(或对应仓库)。
343
-
344
- ---
345
-
346
- ## 日志:log4js 集成
347
-
348
- 配置项类型:
349
-
350
- ```ts
351
- type TLog4 = boolean | ((instance: Log4js) => Log4js);
352
- ```
353
-
354
- - 传入 `false` 或不传:不启用 log4
355
- - 传入 `true`:使用默认 log4 配置
356
- - 传入函数:自定义 log4 配置
357
-
358
- 默认配置示例(`log4: true`):
359
-
360
- ```js
361
- log4js.configure({
362
- appenders: {
363
- console: { type: "console" },
364
- file: {
365
- type: "dateFile",
366
- filename: "logs/app.log",
367
- pattern: ".yyyy-MM-dd",
368
- compress: true,
369
- numBackups: 7,
370
- alwaysIncludePattern: true,
371
- },
372
- },
373
- categories: {
374
- default: { appenders: ["console", "file"], level: "info" },
375
- },
376
- });
377
- ```
378
-
379
- 自定义示例:
553
+ `koa-ts-core` 提供路由元信息,配合 `koa-ts-cli` 的 `koa-ts-cli doc` 命令,可以根据 `src/controller` 自动生成接口配置,并在运行时通过 `/doc` 路由查看渲染后的接口文档(仅开发环境或 `DOC=true` 时启用)。
380
554
 
381
- ```ts
382
- initializeKoaApp({
383
- log4: (instance) => {
384
- return instance.configure({
385
- appenders: { console: { type: "console" } },
386
- categories: {
387
- default: { appenders: ["console"], level: "debug" },
388
- },
389
- });
390
- },
391
- });
392
- ```
555
+ 详细 CLI 使用方式参考:[koa-ts-cli](https://www.npmjs.com/package/koa-typescript-cli)。
393
556
 
394
557
  ---
395
558
 
396
- ## Context 扩展
559
+ ## Context 扩展(部分示意)
397
560
 
398
- `koa-ts-core` `Koa.Context` 做了类型拓展:
561
+ 框架对 `Koa.Context` 做了类型拓展,你可以在业务代码中使用这些字段:
399
562
 
400
563
  ```ts
401
564
  declare module "koa" {
@@ -416,6 +579,9 @@ declare module "koa" {
416
579
  post: Record<string, any>;
417
580
  };
418
581
 
582
+ // trackId(请求 ID)
583
+ trackId?: string;
584
+
419
585
  // 业务扩展字段
420
586
  extra: {
421
587
  get: Record<string, any>;
@@ -425,8 +591,6 @@ declare module "koa" {
425
591
  }
426
592
  ```
427
593
 
428
- ---
429
-
430
594
  ## 相关项目
431
595
 
432
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