@keq-request/nestjs 5.0.0-beta.8 → 5.0.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/dist/index.mjs CHANGED
@@ -1,7 +1,114 @@
1
- import { KeqRequest } from "keq";
2
- import { ConfigurableModuleBuilder, Global } from "@nestjs/common";
3
- //#region src/keq.module-definition.ts
4
- const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN, OPTIONS_TYPE, ASYNC_OPTIONS_TYPE } = new ConfigurableModuleBuilder().build();
1
+ import { Global, Inject, Injectable, Module } from "@nestjs/common";
2
+ import { KeqRequest, composeRoute } from "keq";
3
+ import picomatch from "picomatch";
4
+ //#region src/constants.ts
5
+ const KEQ_ROUTES = { ALL: Symbol("KEQ_ROUTES.ALL") };
6
+ //#endregion
7
+ //#region src/keq-middleware-collector.ts
8
+ /**
9
+ * 中间件收集器,收集中间件配置条目并应用到指定的 {@link KeqRequest} 实例。
10
+ *
11
+ * 通过 `apply()` → `forRoutes()` 链式 API 收集多组中间件条目,
12
+ * 在 `forRoutes()` 被调用时立即将中间件绑定到目标请求。
13
+ *
14
+ * 注意:该类并非 `@Injectable()`,由 Consumer 内部手动创建。
15
+ *
16
+ * @typeParam TConsumer - Consumer 类型(`KeqMiddlewareConsumer` 或 `KeqConsumer<T>`)
17
+ */
18
+ var KeqMiddlewareCollector = class {
19
+ entries = [];
20
+ constructor(keqRequest, consumer) {
21
+ this.keqRequest = keqRequest;
22
+ this.consumer = consumer;
23
+ }
24
+ apply(middlewares) {
25
+ const entry = {
26
+ middlewares,
27
+ routes: []
28
+ };
29
+ const excludedRouteInfos = [];
30
+ this.entries.push(entry);
31
+ const { keqRequest, consumer } = this;
32
+ const proxy = {
33
+ exclude: (...routes) => {
34
+ excludedRouteInfos.push(...routes);
35
+ return proxy;
36
+ },
37
+ forRoutes: (...routes) => {
38
+ entry.routes = routes;
39
+ if (excludedRouteInfos.length > 0) entry.excludedRouteInfos = excludedRouteInfos;
40
+ this.applyTo(keqRequest);
41
+ return consumer;
42
+ }
43
+ };
44
+ return proxy;
45
+ }
46
+ /**
47
+ * 将收集的所有中间件条目解析并应用到指定的 {@link KeqRequest} 实例。
48
+ */
49
+ applyTo(keqRequest) {
50
+ for (const entry of this.entries) {
51
+ let resolved = entry.middlewares.map((m) => this.normalizeMiddleware(m));
52
+ if (entry.excludedRouteInfos && entry.excludedRouteInfos.length > 0) {
53
+ const excludedRoutes = entry.excludedRouteInfos.map((info) => this.buildRoute(info));
54
+ resolved = resolved.map((mw) => this.wrapWithExclusion(mw, excludedRoutes));
55
+ }
56
+ if (entry.routes.length === 0 || entry.routes.some((r) => r === KEQ_ROUTES.ALL)) for (const mw of resolved) keqRequest.use(mw);
57
+ else for (const routeTarget of entry.routes) {
58
+ if (routeTarget === KEQ_ROUTES.ALL) continue;
59
+ const route = this.buildRoute(routeTarget);
60
+ keqRequest.useRouter().route(route, resolved);
61
+ }
62
+ }
63
+ }
64
+ /**
65
+ * 标准化中间件:将不同形式的中间件统一为 {@link KeqMiddleware} 函数。
66
+ * - 若已是 {@link KeqMiddleware} 函数 → 直接返回
67
+ * - 若为 {@link KeqNestMiddleware} 实例对象 → 包装 `use` 方法为中间件函数
68
+ */
69
+ normalizeMiddleware(m) {
70
+ if (this.isNestMiddlewareInstance(m)) return async (ctx, next) => {
71
+ await m.use(ctx, next);
72
+ };
73
+ return m;
74
+ }
75
+ isNestMiddlewareInstance(m) {
76
+ return typeof m === "object" && m !== null && "use" in m;
77
+ }
78
+ buildRoute(info) {
79
+ const routes = [];
80
+ if (info.host) {
81
+ const host = info.host;
82
+ routes.push((ctx) => ctx.request.url.host === host);
83
+ }
84
+ if (info.method) {
85
+ const method = info.method.toLowerCase();
86
+ routes.push((ctx) => ctx.request.method.toLowerCase() === method);
87
+ }
88
+ if (info.pathname) {
89
+ const isMatch = picomatch(info.pathname);
90
+ routes.push((ctx) => isMatch(ctx.request.url.pathname));
91
+ }
92
+ if (routes.length === 1) return routes[0];
93
+ return composeRoute(routes);
94
+ }
95
+ wrapWithExclusion(middleware, excludedRoutes) {
96
+ const excluded = async (ctx, next) => {
97
+ if (await this.checkExcluded(ctx, excludedRoutes)) return next();
98
+ return middleware(ctx, next);
99
+ };
100
+ return excluded;
101
+ }
102
+ async checkExcluded(ctx, excludedRoutes) {
103
+ for (const route of excludedRoutes) if (await route(ctx)) return true;
104
+ return false;
105
+ }
106
+ };
107
+ //#endregion
108
+ //#region \0@oxc-project+runtime@0.127.0/helpers/decorateMetadata.js
109
+ function __decorateMetadata(k, v) {
110
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
111
+ }
5
112
  //#endregion
6
113
  //#region \0@oxc-project+runtime@0.127.0/helpers/decorate.js
7
114
  function __decorate(decorators, target, key, desc) {
@@ -11,47 +118,77 @@ function __decorate(decorators, target, key, desc) {
11
118
  return c > 3 && r && Object.defineProperty(target, key, r), r;
12
119
  }
13
120
  //#endregion
121
+ //#region src/keq-middleware-consumer.ts
122
+ var _ref;
123
+ let KeqMiddlewareConsumer = class KeqMiddlewareConsumer {
124
+ constructor(keqRequest) {
125
+ this.keqRequest = keqRequest;
126
+ }
127
+ apply(...middlewares) {
128
+ return new KeqMiddlewareCollector(this.keqRequest, this).apply(middlewares);
129
+ }
130
+ };
131
+ KeqMiddlewareConsumer = __decorate([Injectable(), __decorateMetadata("design:paramtypes", [typeof (_ref = typeof KeqRequest !== "undefined" && KeqRequest) === "function" ? _ref : Object])], KeqMiddlewareConsumer);
132
+ //#endregion
14
133
  //#region src/keq.module.ts
134
+ let KeqModule = class KeqModule {};
135
+ KeqModule = __decorate([Global(), Module({
136
+ providers: [{
137
+ provide: KeqRequest,
138
+ useFactory: () => new KeqRequest()
139
+ }, KeqMiddlewareConsumer],
140
+ exports: [KeqRequest, KeqMiddlewareConsumer]
141
+ })], KeqModule);
142
+ //#endregion
143
+ //#region src/keq-consumer.ts
15
144
  /**
16
- * Provider that creates and configures a KeqRequest instance
17
- * Applies any middlewares defined in the module options
145
+ * 为指定 Keq 模块按路由注册中间件。
146
+ *
147
+ * Keq 模块由 `@keq-request/cli` 生成,通过
148
+ * {@link InjectKeqConsumer} 装饰器注入本实例。
149
+ *
150
+ * @typeParam T - 目标模块类
151
+ *
152
+ * @example
153
+ * ```ts
154
+ * constructor(
155
+ * \@InjectKeqConsumer(GeneratedModule) consumer: KeqConsumer<GeneratedModule>,
156
+ * ) {
157
+ * consumer.apply(authMw).forRoutes('*')
158
+ * }
159
+ * ```
18
160
  */
19
- const requestProvider = {
20
- provide: KeqRequest,
21
- useFactory: (config) => {
22
- const request = new KeqRequest();
23
- if (config.middlewares) for (const middleware of config.middlewares) request.use(middleware);
24
- return request;
25
- },
26
- inject: [MODULE_OPTIONS_TOKEN]
27
- };
28
- let KeqModule = class KeqModule extends ConfigurableModuleClass {
29
- /**
30
- * Register the module with synchronous options
31
- * @param options - Configuration options including middlewares
32
- * @returns DynamicModule with KeqRequest provider
33
- */
34
- static register(options) {
35
- const mo = super.register(options);
36
- mo.providers.push(requestProvider);
37
- mo.global = true;
38
- return mo;
161
+ var KeqConsumer = class {
162
+ constructor(keqRequest) {
163
+ this.keqRequest = keqRequest;
39
164
  }
40
- /**
41
- * Register the module with asynchronous options
42
- * Useful when you need to inject dependencies like ConfigService
43
- * @param options - Async configuration options
44
- * @returns DynamicModule with KeqRequest provider
45
- */
46
- static registerAsync(options) {
47
- const mo = super.registerAsync(options);
48
- mo.providers.push(requestProvider);
49
- mo.global = true;
50
- return mo;
165
+ apply(...middlewares) {
166
+ return new KeqMiddlewareCollector(this.keqRequest, this).apply(middlewares);
51
167
  }
52
168
  };
53
- KeqModule = __decorate([Global()], KeqModule);
54
169
  //#endregion
55
- export { KeqModule };
170
+ //#region src/decorators/inject-keq-consumer.decorator.ts
171
+ /**
172
+ * 注入绑定到指定 Keq Module 的 `KeqConsumer<T>`。
173
+ *
174
+ * 被注入的 Module Class 必须同时包含 `KEQ_REQUEST` 和 `KEQ_CONSUMER` 静态属性,
175
+ * 两者均由 keq CLI 生成。
176
+ *
177
+ * 使用方式:
178
+ * ```ts
179
+ * constructor(
180
+ * \@InjectKeqConsumer(GeneratedModule) consumer: KeqConsumer<GeneratedModule>,
181
+ * ) {
182
+ * consumer.apply(mw).forRoutes('*')
183
+ * }
184
+ * ```
185
+ *
186
+ * @param moduleClass - 目标 KeqModule 类(需具有 `KEQ_REQUEST` 和 `KEQ_CONSUMER` symbol)
187
+ */
188
+ function InjectKeqConsumer(moduleClass) {
189
+ return Inject(moduleClass.KEQ_CONSUMER);
190
+ }
191
+ //#endregion
192
+ export { InjectKeqConsumer, KEQ_ROUTES, KeqConsumer, KeqMiddlewareConsumer, KeqModule };
56
193
 
57
194
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/keq.module-definition.ts","../src/keq.module.ts"],"sourcesContent":["\nimport { ConfigurableModuleBuilder } from '@nestjs/common'\nimport { KeqModuleOptions } from './types/keq-module-options'\n\n\nexport const {\n ConfigurableModuleClass,\n MODULE_OPTIONS_TOKEN,\n OPTIONS_TYPE,\n ASYNC_OPTIONS_TYPE,\n} = new ConfigurableModuleBuilder<KeqModuleOptions>().build()\n","\nimport { KeqRequest } from 'keq'\nimport { DynamicModule, Global, Provider } from '@nestjs/common'\nimport { ASYNC_OPTIONS_TYPE, ConfigurableModuleClass, MODULE_OPTIONS_TOKEN, OPTIONS_TYPE } from './keq.module-definition.js'\nimport { KeqModuleOptions } from './types/index.js'\n\n\n/**\n * Provider that creates and configures a KeqRequest instance\n * Applies any middlewares defined in the module options\n */\nconst requestProvider: Provider = {\n provide: KeqRequest,\n useFactory: (config: KeqModuleOptions) => {\n const request = new KeqRequest()\n\n if (config.middlewares) {\n for (const middleware of config.middlewares) {\n request.use(middleware)\n }\n }\n\n return request\n },\n inject: [MODULE_OPTIONS_TOKEN],\n}\n\n/**\n * KeqModule - Dynamic module for integrating Keq HTTP client with NestJS\n *\n * This module is global, so KeqRequest can be injected anywhere in your application\n * without needing to import the module in every feature module.\n *\n * @example\n * ```typescript\n * // Synchronous registration\n * KeqModule.register({\n * middlewares: [...]\n * })\n *\n * // Asynchronous registration\n * KeqModule.registerAsync({\n * imports: [ConfigModule],\n * useFactory: (config: ConfigService) => ({\n * middlewares: [...]\n * }),\n * inject: [ConfigService]\n * })\n *\n * // Inject in service\n * class UserService {\n * constructor(private readonly keqRequest: KeqRequest) {}\n * async getUser(id: string) {\n * return await this.keqRequest.get(`/users/${id}`).resolveWith('json')\n * }\n * }\n * ```\n */\n@Global()\nexport class KeqModule extends ConfigurableModuleClass {\n /**\n * Register the module with synchronous options\n * @param options - Configuration options including middlewares\n * @returns DynamicModule with KeqRequest provider\n */\n static register(options: typeof OPTIONS_TYPE): DynamicModule {\n const mo = super.register(options)\n mo.providers!.push(requestProvider)\n mo.global = true\n\n return mo\n }\n\n /**\n * Register the module with asynchronous options\n * Useful when you need to inject dependencies like ConfigService\n * @param options - Async configuration options\n * @returns DynamicModule with KeqRequest provider\n */\n static registerAsync(options: typeof ASYNC_OPTIONS_TYPE): DynamicModule {\n const mo = super.registerAsync(options)\n mo.providers!.push(requestProvider)\n mo.global = true\n\n return mo\n }\n}\n"],"mappings":";;;AAKA,MAAa,EACX,yBACA,sBACA,cACA,uBACE,IAAI,2BAA6C,CAAC,OAAO;;;;;;;;;;;;;;;ACC7D,MAAM,kBAA4B;CAChC,SAAS;CACT,aAAa,WAA6B;EACxC,MAAM,UAAU,IAAI,YAAY;AAEhC,MAAI,OAAO,YACT,MAAK,MAAM,cAAc,OAAO,YAC9B,SAAQ,IAAI,WAAW;AAI3B,SAAO;;CAET,QAAQ,CAAC,qBAAqB;CAC/B;AAkCM,IAAA,YAAA,MAAM,kBAAkB,wBAAwB;;;;;;CAMrD,OAAO,SAAS,SAA6C;EAC3D,MAAM,KAAK,MAAM,SAAS,QAAQ;AAClC,KAAG,UAAW,KAAK,gBAAgB;AACnC,KAAG,SAAS;AAEZ,SAAO;;;;;;;;CAST,OAAO,cAAc,SAAmD;EACtE,MAAM,KAAK,MAAM,cAAc,QAAQ;AACvC,KAAG,UAAW,KAAK,gBAAgB;AACnC,KAAG,SAAS;AAEZ,SAAO;;;wBA1BV,QAAQ,CAAA,EAAA,UAAA"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/constants.ts","../src/keq-middleware-collector.ts","../src/keq-middleware-consumer.ts","../src/keq.module.ts","../src/keq-consumer.ts","../src/decorators/inject-keq-consumer.decorator.ts"],"sourcesContent":["export const KEQ_ROUTES = {\n ALL: Symbol('KEQ_ROUTES.ALL'),\n} as const\n","import type { KeqExecutionContext, KeqMiddleware, KeqRoute } from 'keq'\nimport { composeRoute, KeqRequest } from 'keq'\nimport picomatch from 'picomatch'\nimport { KEQ_ROUTES } from './constants.js'\nimport type { KeqMiddlewareConfigProxy, KeqRouteTarget, KeqRouteInfo } from './interfaces/keq-middleware-consumer.interface.js'\nimport type { KeqNestMiddleware } from './interfaces/keq-nest-middleware.interface.js'\n\n\n/** 单条中间件注册条目 */\ninterface MiddlewareEntry {\n middlewares: Array<KeqNestMiddleware | KeqMiddleware>\n routes: KeqRouteTarget[]\n excludedRouteInfos?: KeqRouteInfo[]\n}\n\n/**\n * 中间件收集器,收集中间件配置条目并应用到指定的 {@link KeqRequest} 实例。\n *\n * 通过 `apply()` → `forRoutes()` 链式 API 收集多组中间件条目,\n * 在 `forRoutes()` 被调用时立即将中间件绑定到目标请求。\n *\n * 注意:该类并非 `@Injectable()`,由 Consumer 内部手动创建。\n *\n * @typeParam TConsumer - Consumer 类型(`KeqMiddlewareConsumer` 或 `KeqConsumer<T>`)\n */\nexport class KeqMiddlewareCollector<TConsumer extends object = object> {\n private entries: MiddlewareEntry[] = []\n\n constructor(\n private readonly keqRequest: KeqRequest,\n private readonly consumer: TConsumer,\n ) {}\n\n apply(\n middlewares: Array<KeqNestMiddleware | KeqMiddleware>,\n ): KeqMiddlewareConfigProxy {\n const entry: MiddlewareEntry = { middlewares, routes: [] }\n const excludedRouteInfos: KeqRouteInfo[] = []\n this.entries.push(entry)\n\n const { keqRequest, consumer } = this\n\n const proxy = {\n exclude: (...routes: KeqRouteInfo[]) => {\n excludedRouteInfos.push(...routes)\n return proxy\n },\n forRoutes: (...routes: KeqRouteTarget[]) => {\n entry.routes = routes\n if (excludedRouteInfos.length > 0) {\n entry.excludedRouteInfos = excludedRouteInfos\n }\n this.applyTo(keqRequest)\n return consumer\n },\n }\n return proxy as unknown as KeqMiddlewareConfigProxy\n }\n\n /**\n * 将收集的所有中间件条目解析并应用到指定的 {@link KeqRequest} 实例。\n */\n applyTo(keqRequest: KeqRequest): void {\n for (const entry of this.entries) {\n let resolved = entry.middlewares.map((m) => this.normalizeMiddleware(m))\n\n if (entry.excludedRouteInfos && entry.excludedRouteInfos.length > 0) {\n const excludedRoutes = entry.excludedRouteInfos.map((info) => this.buildRoute(info))\n resolved = resolved.map((mw) => this.wrapWithExclusion(mw, excludedRoutes))\n }\n\n const isGlobal\n = entry.routes.length === 0 || entry.routes.some((r) => r === KEQ_ROUTES.ALL)\n\n if (isGlobal) {\n for (const mw of resolved) keqRequest.use(mw)\n } else {\n for (const routeTarget of entry.routes) {\n if (routeTarget === KEQ_ROUTES.ALL) continue\n const route = this.buildRoute(routeTarget as KeqRouteInfo)\n keqRequest.useRouter().route(route, resolved)\n }\n }\n }\n }\n\n // ─── 中间件标准化 ────────────────────────────────────\n\n /**\n * 标准化中间件:将不同形式的中间件统一为 {@link KeqMiddleware} 函数。\n * - 若已是 {@link KeqMiddleware} 函数 → 直接返回\n * - 若为 {@link KeqNestMiddleware} 实例对象 → 包装 `use` 方法为中间件函数\n */\n private normalizeMiddleware(\n m: KeqNestMiddleware | KeqMiddleware,\n ): KeqMiddleware {\n if (this.isNestMiddlewareInstance(m)) {\n return async (ctx, next) => {\n await m.use(ctx, next)\n }\n }\n return m\n }\n\n private isNestMiddlewareInstance(\n m: KeqNestMiddleware | KeqMiddleware,\n ): m is KeqNestMiddleware {\n return typeof m === 'object' && m !== null && 'use' in m\n }\n\n // ─── 路由构建 ─────────────────────────────────────────\n\n private buildRoute(info: KeqRouteInfo): KeqRoute {\n const routes: KeqRoute[] = []\n if (info.host) {\n const host = info.host\n routes.push((ctx) => ctx.request.url.host === host)\n }\n if (info.method) {\n const method = info.method.toLowerCase()\n routes.push((ctx) => ctx.request.method.toLowerCase() === method)\n }\n if (info.pathname) {\n const isMatch: (test: string) => boolean = picomatch(info.pathname)\n routes.push((ctx) => isMatch(ctx.request.url.pathname))\n }\n if (routes.length === 1) return routes[0]\n return composeRoute(routes)\n }\n\n private wrapWithExclusion(middleware: KeqMiddleware, excludedRoutes: KeqRoute[]): KeqMiddleware {\n const excluded: KeqMiddleware = async (ctx, next) => {\n if (await this.checkExcluded(ctx, excludedRoutes)) {\n return next()\n }\n return middleware(ctx, next)\n }\n return excluded\n }\n\n private async checkExcluded(\n ctx: KeqExecutionContext,\n excludedRoutes: KeqRoute[],\n ): Promise<boolean> {\n for (const route of excludedRoutes) {\n if (await route(ctx)) return true\n }\n return false\n }\n}\n","import { Injectable } from '@nestjs/common'\nimport type { KeqMiddleware } from 'keq'\nimport { KeqRequest } from 'keq'\nimport type { KeqMiddlewareConfigProxy } from './interfaces/keq-middleware-consumer.interface.js'\nimport type { KeqNestMiddleware } from './interfaces/keq-nest-middleware.interface.js'\nimport { KeqMiddlewareCollector } from './keq-middleware-collector.js'\n\n\n/**\n * 全局中间件消费者,提供 `.apply().forRoutes()` API。\n *\n * `forRoutes()` 返回 `KeqMiddlewareConsumer` 自身,支持链式注册:\n *\n * ```ts\n * consumer\n * .apply(mw1).forRoutes(KEQ_ROUTES.ALL)\n * .apply(mw2).forRoutes({ pathname: '/api/*' })\n * ```\n *\n * 模块级别的中间件请使用 `@InjectKeqConsumer(GeneratedModule)` 注入\n * `KeqConsumer<GeneratedModule>`,其 `forRoutes()` 直接作用于目标模块。\n */\n@Injectable()\nexport class KeqMiddlewareConsumer {\n constructor(private readonly keqRequest: KeqRequest) {}\n\n apply(\n ...middlewares: Array<KeqNestMiddleware | KeqMiddleware>\n ): KeqMiddlewareConfigProxy {\n const collector = new KeqMiddlewareCollector(this.keqRequest, this)\n return collector.apply(middlewares)\n }\n}\n","import { Global, Module } from '@nestjs/common'\nimport { KeqRequest } from 'keq'\nimport { KeqMiddlewareConsumer } from './keq-middleware-consumer.js'\n\n\n@Global()\n@Module({\n providers: [\n { provide: KeqRequest, useFactory: () => new KeqRequest() },\n KeqMiddlewareConsumer,\n ],\n exports: [KeqRequest, KeqMiddlewareConsumer],\n})\nexport class KeqModule {}\n","import type { KeqMiddleware } from 'keq'\nimport { KeqRequest } from 'keq'\nimport type { KeqModuleClass, KeqScopedConfigProxy } from './interfaces/keq-middleware-consumer.interface.js'\nimport type { KeqNestMiddleware } from './interfaces/keq-nest-middleware.interface.js'\nimport { KeqMiddlewareCollector } from './keq-middleware-collector.js'\n\n\n/**\n * 为指定 Keq 模块按路由注册中间件。\n *\n * Keq 模块由 `@keq-request/cli` 生成,通过\n * {@link InjectKeqConsumer} 装饰器注入本实例。\n *\n * @typeParam T - 目标模块类\n *\n * @example\n * ```ts\n * constructor(\n * \\@InjectKeqConsumer(GeneratedModule) consumer: KeqConsumer<GeneratedModule>,\n * ) {\n * consumer.apply(authMw).forRoutes('*')\n * }\n * ```\n */\nexport class KeqConsumer<T = KeqModuleClass> {\n constructor(private readonly keqRequest: KeqRequest) {}\n\n apply(\n ...middlewares: Array<KeqNestMiddleware | KeqMiddleware>\n ): KeqScopedConfigProxy<T> {\n const collector = new KeqMiddlewareCollector(this.keqRequest, this)\n return collector.apply(middlewares) as unknown as KeqScopedConfigProxy<T>\n }\n}\n","import { Inject } from '@nestjs/common'\nimport type { KeqModuleClass } from '../interfaces/keq-middleware-consumer.interface.js'\n\n\n/**\n * 注入绑定到指定 Keq Module 的 `KeqConsumer<T>`。\n *\n * 被注入的 Module Class 必须同时包含 `KEQ_REQUEST` 和 `KEQ_CONSUMER` 静态属性,\n * 两者均由 keq CLI 生成。\n *\n * 使用方式:\n * ```ts\n * constructor(\n * \\@InjectKeqConsumer(GeneratedModule) consumer: KeqConsumer<GeneratedModule>,\n * ) {\n * consumer.apply(mw).forRoutes('*')\n * }\n * ```\n *\n * @param moduleClass - 目标 KeqModule 类(需具有 `KEQ_REQUEST` 和 `KEQ_CONSUMER` symbol)\n */\nexport function InjectKeqConsumer<T extends KeqModuleClass>(\n moduleClass: T,\n): ParameterDecorator {\n return Inject(moduleClass.KEQ_CONSUMER)\n}\n"],"mappings":"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"}
package/jest.config.cts CHANGED
@@ -5,6 +5,16 @@ import { compilerOptions } from './tsconfig.json'
5
5
 
6
6
  // eslint-disable-next-line @typescript-eslint/require-await
7
7
  export default async (): Promise<Config> => ({
8
- preset: 'ts-jest',
9
- moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/src', useESM: true }),
8
+ transform: {
9
+ '^.+\\.tsx?$': ['ts-jest', {
10
+ tsconfig: {
11
+ noEmitOnError: false,
12
+ },
13
+ }],
14
+ },
15
+ testMatch: [
16
+ '<rootDir>/__tests__/**/*.spec.ts',
17
+ '<rootDir>/src/**/*.spec.ts',
18
+ ],
19
+ moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>', useESM: true }),
10
20
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keq-request/nestjs",
3
- "version": "5.0.0-beta.8",
3
+ "version": "5.0.0",
4
4
  "description": "Request API write by Typescript for flexibility, readability, and a low learning curve.",
5
5
  "keywords": [
6
6
  "request",
@@ -33,14 +33,22 @@
33
33
  "type": "git",
34
34
  "url": "git+https://github.com/keq-request/keq.git"
35
35
  },
36
+ "dependencies": {
37
+ "picomatch": "^4.0.0"
38
+ },
36
39
  "devDependencies": {
37
40
  "@nestjs/common": "^11.1.19",
41
+ "@nestjs/core": "^11.1.19",
42
+ "@nestjs/testing": "^11.1.27",
38
43
  "@types/node": "^20.19.39",
39
- "keq": "5.0.0-beta.8"
44
+ "@types/picomatch": "^4.0.0",
45
+ "reflect-metadata": "^0.2.2",
46
+ "keq": "5.0.0"
40
47
  },
41
48
  "peerDependencies": {
42
49
  "@nestjs/common": "^11.0.0",
43
- "keq": "^5.0.0-beta.8"
50
+ "@nestjs/core": "^11.0.0",
51
+ "keq": "^5.0.0"
44
52
  },
45
53
  "engines": {
46
54
  "node": ">=20.0.0"
@@ -0,0 +1,3 @@
1
+ export const KEQ_ROUTES = {
2
+ ALL: Symbol('KEQ_ROUTES.ALL'),
3
+ } as const
@@ -0,0 +1,26 @@
1
+ import { Inject } from '@nestjs/common'
2
+ import type { KeqModuleClass } from '../interfaces/keq-middleware-consumer.interface.js'
3
+
4
+
5
+ /**
6
+ * 注入绑定到指定 Keq Module 的 `KeqConsumer<T>`。
7
+ *
8
+ * 被注入的 Module Class 必须同时包含 `KEQ_REQUEST` 和 `KEQ_CONSUMER` 静态属性,
9
+ * 两者均由 keq CLI 生成。
10
+ *
11
+ * 使用方式:
12
+ * ```ts
13
+ * constructor(
14
+ * \@InjectKeqConsumer(GeneratedModule) consumer: KeqConsumer<GeneratedModule>,
15
+ * ) {
16
+ * consumer.apply(mw).forRoutes('*')
17
+ * }
18
+ * ```
19
+ *
20
+ * @param moduleClass - 目标 KeqModule 类(需具有 `KEQ_REQUEST` 和 `KEQ_CONSUMER` symbol)
21
+ */
22
+ export function InjectKeqConsumer<T extends KeqModuleClass>(
23
+ moduleClass: T,
24
+ ): ParameterDecorator {
25
+ return Inject(moduleClass.KEQ_CONSUMER)
26
+ }
package/src/index.ts CHANGED
@@ -1,2 +1,6 @@
1
1
  export * from './keq.module.js'
2
- export * from './types/index.js'
2
+ export * from './keq-middleware-consumer.js'
3
+ export * from './keq-consumer.js'
4
+ export * from './constants.js'
5
+ export * from './interfaces/index.js'
6
+ export { InjectKeqConsumer } from './decorators/inject-keq-consumer.decorator.js'
@@ -0,0 +1,9 @@
1
+ export type { KeqNestMiddleware } from './keq-nest-middleware.interface.js'
2
+ export type {
3
+ KeqMiddlewareConfigProxy,
4
+ KeqScopedConfigProxy,
5
+ KeqRouteInfo,
6
+ KeqRouteTarget,
7
+ KeqModuleClass,
8
+ } from './keq-middleware-consumer.interface.js'
9
+ export type { KeqModuleOptions } from './keq-module-options.interface.js'
@@ -0,0 +1,30 @@
1
+ import type { Type } from '@nestjs/common'
2
+ import type { KEQ_ROUTES } from '../constants.js'
3
+ import type { KeqMiddlewareConsumer } from '../keq-middleware-consumer.js'
4
+ import type { KeqConsumer } from '../keq-consumer.js'
5
+
6
+
7
+ export interface KeqRouteInfo {
8
+ host?: string
9
+ method?: string
10
+ pathname?: string
11
+ }
12
+
13
+ export interface KeqModuleClass extends Type<any> {
14
+ readonly KEQ_REQUEST: symbol
15
+ readonly KEQ_CONSUMER: symbol
16
+ }
17
+
18
+ /** forRoutes() 接受的路由目标(不再包含 KeqModuleClass,模块绑定通过 @InjectKeqConsumer 实现) */
19
+ export type KeqRouteTarget = typeof KEQ_ROUTES.ALL | KeqRouteInfo
20
+
21
+ export interface KeqMiddlewareConfigProxy {
22
+ exclude(...routes: KeqRouteInfo[]): KeqMiddlewareConfigProxy
23
+ forRoutes(...routes: KeqRouteTarget[]): KeqMiddlewareConsumer
24
+ }
25
+
26
+ /** 模块绑定 Consumer 的配置代理,forRoutes() 返回 KeqConsumer<T> */
27
+ export interface KeqScopedConfigProxy<T = KeqModuleClass> {
28
+ exclude(...routes: KeqRouteInfo[]): KeqScopedConfigProxy<T>
29
+ forRoutes(...routes: KeqRouteTarget[]): KeqConsumer<T>
30
+ }
@@ -1,6 +1,7 @@
1
- import { KeqMiddleware } from 'keq'
1
+ import type { KeqMiddleware } from 'keq'
2
2
 
3
3
 
4
4
  export interface KeqModuleOptions {
5
5
  middlewares?: KeqMiddleware[]
6
+ isolate?: boolean
6
7
  }
@@ -0,0 +1,6 @@
1
+ import type { KeqExecutionContext, KeqNext } from 'keq'
2
+
3
+
4
+ export interface KeqNestMiddleware {
5
+ use(ctx: KeqExecutionContext, next: KeqNext): void | PromiseLike<void>
6
+ }
@@ -0,0 +1,34 @@
1
+ import type { KeqMiddleware } from 'keq'
2
+ import { KeqRequest } from 'keq'
3
+ import type { KeqModuleClass, KeqScopedConfigProxy } from './interfaces/keq-middleware-consumer.interface.js'
4
+ import type { KeqNestMiddleware } from './interfaces/keq-nest-middleware.interface.js'
5
+ import { KeqMiddlewareCollector } from './keq-middleware-collector.js'
6
+
7
+
8
+ /**
9
+ * 为指定 Keq 模块按路由注册中间件。
10
+ *
11
+ * Keq 模块由 `@keq-request/cli` 生成,通过
12
+ * {@link InjectKeqConsumer} 装饰器注入本实例。
13
+ *
14
+ * @typeParam T - 目标模块类
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * constructor(
19
+ * \@InjectKeqConsumer(GeneratedModule) consumer: KeqConsumer<GeneratedModule>,
20
+ * ) {
21
+ * consumer.apply(authMw).forRoutes('*')
22
+ * }
23
+ * ```
24
+ */
25
+ export class KeqConsumer<T = KeqModuleClass> {
26
+ constructor(private readonly keqRequest: KeqRequest) {}
27
+
28
+ apply(
29
+ ...middlewares: Array<KeqNestMiddleware | KeqMiddleware>
30
+ ): KeqScopedConfigProxy<T> {
31
+ const collector = new KeqMiddlewareCollector(this.keqRequest, this)
32
+ return collector.apply(middlewares) as unknown as KeqScopedConfigProxy<T>
33
+ }
34
+ }
@@ -0,0 +1,150 @@
1
+ import type { KeqExecutionContext, KeqMiddleware, KeqRoute } from 'keq'
2
+ import { composeRoute, KeqRequest } from 'keq'
3
+ import picomatch from 'picomatch'
4
+ import { KEQ_ROUTES } from './constants.js'
5
+ import type { KeqMiddlewareConfigProxy, KeqRouteTarget, KeqRouteInfo } from './interfaces/keq-middleware-consumer.interface.js'
6
+ import type { KeqNestMiddleware } from './interfaces/keq-nest-middleware.interface.js'
7
+
8
+
9
+ /** 单条中间件注册条目 */
10
+ interface MiddlewareEntry {
11
+ middlewares: Array<KeqNestMiddleware | KeqMiddleware>
12
+ routes: KeqRouteTarget[]
13
+ excludedRouteInfos?: KeqRouteInfo[]
14
+ }
15
+
16
+ /**
17
+ * 中间件收集器,收集中间件配置条目并应用到指定的 {@link KeqRequest} 实例。
18
+ *
19
+ * 通过 `apply()` → `forRoutes()` 链式 API 收集多组中间件条目,
20
+ * 在 `forRoutes()` 被调用时立即将中间件绑定到目标请求。
21
+ *
22
+ * 注意:该类并非 `@Injectable()`,由 Consumer 内部手动创建。
23
+ *
24
+ * @typeParam TConsumer - Consumer 类型(`KeqMiddlewareConsumer` 或 `KeqConsumer<T>`)
25
+ */
26
+ export class KeqMiddlewareCollector<TConsumer extends object = object> {
27
+ private entries: MiddlewareEntry[] = []
28
+
29
+ constructor(
30
+ private readonly keqRequest: KeqRequest,
31
+ private readonly consumer: TConsumer,
32
+ ) {}
33
+
34
+ apply(
35
+ middlewares: Array<KeqNestMiddleware | KeqMiddleware>,
36
+ ): KeqMiddlewareConfigProxy {
37
+ const entry: MiddlewareEntry = { middlewares, routes: [] }
38
+ const excludedRouteInfos: KeqRouteInfo[] = []
39
+ this.entries.push(entry)
40
+
41
+ const { keqRequest, consumer } = this
42
+
43
+ const proxy = {
44
+ exclude: (...routes: KeqRouteInfo[]) => {
45
+ excludedRouteInfos.push(...routes)
46
+ return proxy
47
+ },
48
+ forRoutes: (...routes: KeqRouteTarget[]) => {
49
+ entry.routes = routes
50
+ if (excludedRouteInfos.length > 0) {
51
+ entry.excludedRouteInfos = excludedRouteInfos
52
+ }
53
+ this.applyTo(keqRequest)
54
+ return consumer
55
+ },
56
+ }
57
+ return proxy as unknown as KeqMiddlewareConfigProxy
58
+ }
59
+
60
+ /**
61
+ * 将收集的所有中间件条目解析并应用到指定的 {@link KeqRequest} 实例。
62
+ */
63
+ applyTo(keqRequest: KeqRequest): void {
64
+ for (const entry of this.entries) {
65
+ let resolved = entry.middlewares.map((m) => this.normalizeMiddleware(m))
66
+
67
+ if (entry.excludedRouteInfos && entry.excludedRouteInfos.length > 0) {
68
+ const excludedRoutes = entry.excludedRouteInfos.map((info) => this.buildRoute(info))
69
+ resolved = resolved.map((mw) => this.wrapWithExclusion(mw, excludedRoutes))
70
+ }
71
+
72
+ const isGlobal
73
+ = entry.routes.length === 0 || entry.routes.some((r) => r === KEQ_ROUTES.ALL)
74
+
75
+ if (isGlobal) {
76
+ for (const mw of resolved) keqRequest.use(mw)
77
+ } else {
78
+ for (const routeTarget of entry.routes) {
79
+ if (routeTarget === KEQ_ROUTES.ALL) continue
80
+ const route = this.buildRoute(routeTarget as KeqRouteInfo)
81
+ keqRequest.useRouter().route(route, resolved)
82
+ }
83
+ }
84
+ }
85
+ }
86
+
87
+ // ─── 中间件标准化 ────────────────────────────────────
88
+
89
+ /**
90
+ * 标准化中间件:将不同形式的中间件统一为 {@link KeqMiddleware} 函数。
91
+ * - 若已是 {@link KeqMiddleware} 函数 → 直接返回
92
+ * - 若为 {@link KeqNestMiddleware} 实例对象 → 包装 `use` 方法为中间件函数
93
+ */
94
+ private normalizeMiddleware(
95
+ m: KeqNestMiddleware | KeqMiddleware,
96
+ ): KeqMiddleware {
97
+ if (this.isNestMiddlewareInstance(m)) {
98
+ return async (ctx, next) => {
99
+ await m.use(ctx, next)
100
+ }
101
+ }
102
+ return m
103
+ }
104
+
105
+ private isNestMiddlewareInstance(
106
+ m: KeqNestMiddleware | KeqMiddleware,
107
+ ): m is KeqNestMiddleware {
108
+ return typeof m === 'object' && m !== null && 'use' in m
109
+ }
110
+
111
+ // ─── 路由构建 ─────────────────────────────────────────
112
+
113
+ private buildRoute(info: KeqRouteInfo): KeqRoute {
114
+ const routes: KeqRoute[] = []
115
+ if (info.host) {
116
+ const host = info.host
117
+ routes.push((ctx) => ctx.request.url.host === host)
118
+ }
119
+ if (info.method) {
120
+ const method = info.method.toLowerCase()
121
+ routes.push((ctx) => ctx.request.method.toLowerCase() === method)
122
+ }
123
+ if (info.pathname) {
124
+ const isMatch: (test: string) => boolean = picomatch(info.pathname)
125
+ routes.push((ctx) => isMatch(ctx.request.url.pathname))
126
+ }
127
+ if (routes.length === 1) return routes[0]
128
+ return composeRoute(routes)
129
+ }
130
+
131
+ private wrapWithExclusion(middleware: KeqMiddleware, excludedRoutes: KeqRoute[]): KeqMiddleware {
132
+ const excluded: KeqMiddleware = async (ctx, next) => {
133
+ if (await this.checkExcluded(ctx, excludedRoutes)) {
134
+ return next()
135
+ }
136
+ return middleware(ctx, next)
137
+ }
138
+ return excluded
139
+ }
140
+
141
+ private async checkExcluded(
142
+ ctx: KeqExecutionContext,
143
+ excludedRoutes: KeqRoute[],
144
+ ): Promise<boolean> {
145
+ for (const route of excludedRoutes) {
146
+ if (await route(ctx)) return true
147
+ }
148
+ return false
149
+ }
150
+ }
@@ -0,0 +1,33 @@
1
+ import { Injectable } from '@nestjs/common'
2
+ import type { KeqMiddleware } from 'keq'
3
+ import { KeqRequest } from 'keq'
4
+ import type { KeqMiddlewareConfigProxy } from './interfaces/keq-middleware-consumer.interface.js'
5
+ import type { KeqNestMiddleware } from './interfaces/keq-nest-middleware.interface.js'
6
+ import { KeqMiddlewareCollector } from './keq-middleware-collector.js'
7
+
8
+
9
+ /**
10
+ * 全局中间件消费者,提供 `.apply().forRoutes()` API。
11
+ *
12
+ * `forRoutes()` 返回 `KeqMiddlewareConsumer` 自身,支持链式注册:
13
+ *
14
+ * ```ts
15
+ * consumer
16
+ * .apply(mw1).forRoutes(KEQ_ROUTES.ALL)
17
+ * .apply(mw2).forRoutes({ pathname: '/api/*' })
18
+ * ```
19
+ *
20
+ * 模块级别的中间件请使用 `@InjectKeqConsumer(GeneratedModule)` 注入
21
+ * `KeqConsumer<GeneratedModule>`,其 `forRoutes()` 直接作用于目标模块。
22
+ */
23
+ @Injectable()
24
+ export class KeqMiddlewareConsumer {
25
+ constructor(private readonly keqRequest: KeqRequest) {}
26
+
27
+ apply(
28
+ ...middlewares: Array<KeqNestMiddleware | KeqMiddleware>
29
+ ): KeqMiddlewareConfigProxy {
30
+ const collector = new KeqMiddlewareCollector(this.keqRequest, this)
31
+ return collector.apply(middlewares)
32
+ }
33
+ }