koa-ts-core 0.1.0-dev.0 → 0.1.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.
Files changed (2) hide show
  1. package/README.md +31 -1
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # koa-ts-core
2
2
 
3
- 基于 **TypeScript + Koa** 的轻量服务端核心库,提供:
3
+ 基于 **TypeScript + [Koa3](https://koajs.com/)** 的轻量服务端核心库,提供:
4
4
 
5
5
  - 约定式路由(装饰器)
6
6
  - 权限与参数校验约定
@@ -113,6 +113,36 @@ bootstrap();
113
113
 
114
114
  ---
115
115
 
116
+ ## 获取当前请求上下文
117
+
118
+ 框架通过 `AsyncLocalStorage` 在异步链路中保存 Koa 的 `Context`,从而在**无需显式传递 `ctx` 参数**的情况下,也能获取当前请求的上下文。
119
+
120
+ ### getCurrentContext()
121
+
122
+ ```ts
123
+ import { AsyncLocalStorage } from "async_hooks";
124
+ import type { Context } from "koa";
125
+
126
+ // 全局上下文存储
127
+ export const contextStore = new AsyncLocalStorage<Context>();
128
+
129
+ /**
130
+ * 获取当前请求的 Koa Context
131
+ *
132
+ * 仅在被 AsyncLocalStorage 包裹的异步调用链中生效。
133
+ * 若当前不存在上下文,将抛出异常。
134
+ */
135
+ export const getCurrentContext = (): Context => {
136
+ const context = contextStore.getStore();
137
+ if (!context) {
138
+ throw new Error("context is not exist");
139
+ }
140
+ return context;
141
+ };
142
+ ```
143
+
144
+ ---
145
+
116
146
  ## 中间件链路
117
147
 
118
148
  内置中间件按以下顺序执行:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "koa-ts-core",
3
- "version": "0.1.0-dev.0",
3
+ "version": "0.1.0",
4
4
  "description": "koa-ts-core",
5
5
  "main": "dist/index.cjs.js",
6
6
  "module": "dist/index.esm.js",