q-koa 13.8.29 → 13.8.30
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/core/app.js +35 -16
- package/package.json +1 -1
package/core/app.js
CHANGED
|
@@ -143,22 +143,36 @@ class APP {
|
|
|
143
143
|
// }));
|
|
144
144
|
const { is_off = false } = this.config.restc
|
|
145
145
|
if (!is_off) {
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
146
|
+
/**
|
|
147
|
+
* restc中间件
|
|
148
|
+
* 注意:这里只构建不注册。实例按 appName 惰性创建并缓存(app 数量有限),
|
|
149
|
+
* 避免在中间件内部调用 app.use() 导致 middleware 数组每个请求增长一个实例。
|
|
150
|
+
* 实际注册在 initApp() 中路由注册之后,保持"兜底生效"的原有顺序。
|
|
151
|
+
*/
|
|
152
|
+
const globalExcludes = [...this.config.restc.excludes]
|
|
153
|
+
// 兜底实例:无法识别 appName 时使用原始全局 excludes(不含 appName 前缀)
|
|
154
|
+
const fallbackRestc = restc.koa2({ excludes: globalExcludes })
|
|
155
|
+
const restcCache = new Map()
|
|
156
|
+
this.restcMiddleware = async (ctx, next) => {
|
|
157
|
+
const appName = ctx.request.url.split('/')[1]
|
|
158
|
+
const app = this.app[appName]
|
|
159
|
+
// 未注册应用统一走兜底实例,保证缓存有界(避免随机 appName 撑爆内存)
|
|
160
|
+
if (!app || !app.appConfig) {
|
|
161
|
+
return await fallbackRestc(ctx, next)
|
|
162
|
+
}
|
|
163
|
+
if (!restcCache.has(appName)) {
|
|
164
|
+
const excludes = [
|
|
165
|
+
// 全局 excludes 也必须拼 /${appName}/ 前缀,
|
|
166
|
+
// 否则 Gateway.test 做 indexOf(rule) === 0 前缀匹配时永远不命中
|
|
167
|
+
...globalExcludes.map((item) => `/${appName}/${item}`),
|
|
168
|
+
..._.get(app, 'appConfig.restc.excludes', []).map(
|
|
169
|
+
(item) => `/${appName}/${item}`
|
|
170
|
+
),
|
|
171
|
+
]
|
|
172
|
+
restcCache.set(appName, restc.koa2({ excludes }))
|
|
173
|
+
}
|
|
174
|
+
return await restcCache.get(appName)(ctx, next)
|
|
175
|
+
}
|
|
162
176
|
}
|
|
163
177
|
|
|
164
178
|
/**
|
|
@@ -614,6 +628,11 @@ class APP {
|
|
|
614
628
|
})
|
|
615
629
|
this.app.use(router.routes()).use(router.allowedMethods())
|
|
616
630
|
|
|
631
|
+
// restc 排在路由之后注册:仅当没有其他中间件响应时才兜底生效(保持原有行为)
|
|
632
|
+
if (this.restcMiddleware) {
|
|
633
|
+
this.app.use(this.restcMiddleware)
|
|
634
|
+
}
|
|
635
|
+
|
|
617
636
|
spinner.stop()
|
|
618
637
|
|
|
619
638
|
console.log(chalk.green('==================== end ===================='))
|