@midwayjs/core 3.3.5 → 3.4.0-beta.10

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 (39) hide show
  1. package/dist/baseFramework.d.ts +3 -0
  2. package/dist/baseFramework.js +32 -13
  3. package/dist/common/asyncContextManager.d.ts +61 -0
  4. package/dist/common/asyncContextManager.js +63 -0
  5. package/dist/common/dataSourceManager.d.ts +35 -0
  6. package/dist/common/dataSourceManager.js +127 -0
  7. package/dist/common/fileDetector.d.ts +1 -0
  8. package/dist/common/fileDetector.js +20 -0
  9. package/dist/common/filterManager.d.ts +1 -0
  10. package/dist/common/filterManager.js +37 -5
  11. package/dist/common/serviceFactory.js +2 -1
  12. package/dist/common/webGenerator.d.ts +4 -3
  13. package/dist/common/webGenerator.js +24 -15
  14. package/dist/config/config.default.d.ts +3 -0
  15. package/dist/config/config.default.js +3 -0
  16. package/dist/context/container.js +3 -0
  17. package/dist/error/framework.d.ts +8 -0
  18. package/dist/error/framework.js +15 -1
  19. package/dist/index.d.ts +5 -3
  20. package/dist/index.js +11 -3
  21. package/dist/interface.d.ts +14 -4
  22. package/dist/interface.js +3 -1
  23. package/dist/service/configService.js +7 -4
  24. package/dist/service/frameworkService.js +7 -6
  25. package/dist/service/middlewareService.js +13 -5
  26. package/dist/service/slsFunctionService.d.ts +25 -0
  27. package/dist/service/slsFunctionService.js +242 -0
  28. package/dist/{common/webRouterCollector.d.ts → service/webRouterService.d.ts} +87 -36
  29. package/dist/{common/webRouterCollector.js → service/webRouterService.js} +121 -116
  30. package/dist/setup.js +3 -0
  31. package/dist/util/contextUtil.d.ts +2 -0
  32. package/dist/util/contextUtil.js +6 -1
  33. package/dist/util/index.d.ts +1 -0
  34. package/dist/util/index.js +23 -2
  35. package/dist/util/pathToRegexp.d.ts +113 -7
  36. package/dist/util/pathToRegexp.js +326 -205
  37. package/package.json +3 -3
  38. package/dist/common/triggerCollector.d.ts +0 -8
  39. package/dist/common/triggerCollector.js +0 -37
@@ -1,16 +1,17 @@
1
+ import { ControllerOption } from '@midwayjs/decorator';
1
2
  export interface RouterInfo {
2
3
  /**
3
4
  * uuid
4
5
  */
5
- id: string;
6
+ id?: string;
6
7
  /**
7
8
  * router prefix from controller
8
9
  */
9
- prefix: string;
10
+ prefix?: string;
10
11
  /**
11
12
  * router alias name
12
13
  */
13
- routerName: string;
14
+ routerName?: string;
14
15
  /**
15
16
  * router path, without prefix
16
17
  */
@@ -22,40 +23,43 @@ export interface RouterInfo {
22
23
  /**
23
24
  * invoke function method
24
25
  */
25
- method: string;
26
+ method: string | ((...args: any[]) => void);
26
27
  /**
27
28
  * router description
28
29
  */
29
- description: string;
30
- summary: string;
30
+ description?: string;
31
+ /**
32
+ * @deprecated
33
+ */
34
+ summary?: string;
31
35
  /**
32
36
  * router handler function key,for IoC container load
33
37
  */
34
- handlerName: string;
38
+ handlerName?: string;
35
39
  /**
36
40
  * serverless func load key
37
41
  */
38
- funcHandlerName: string;
42
+ funcHandlerName?: string;
39
43
  /**
40
44
  * controller provideId
41
45
  */
42
- controllerId: string;
46
+ controllerId?: string;
43
47
  /**
44
48
  * router middleware
45
49
  */
46
- middleware: any[];
50
+ middleware?: any[];
47
51
  /**
48
52
  * controller middleware in this router
49
53
  */
50
- controllerMiddleware: any[];
54
+ controllerMiddleware?: any[];
51
55
  /**
52
56
  * request args metadata
53
57
  */
54
- requestMetadata: any[];
58
+ requestMetadata?: any[];
55
59
  /**
56
60
  * response data metadata
57
61
  */
58
- responseMetadata: any[];
62
+ responseMetadata?: any[];
59
63
  /**
60
64
  * serverless function name
61
65
  */
@@ -72,7 +76,20 @@ export interface RouterInfo {
72
76
  * serverless function metadata
73
77
  */
74
78
  functionMetadata?: any;
79
+ /**
80
+ * url with prefix
81
+ */
82
+ fullUrl?: string;
83
+ /**
84
+ * pattern after path-regexp compile
85
+ */
86
+ fullUrlCompiledRegexp?: RegExp;
87
+ /**
88
+ * url after wildcard and can be path-to-regexp by path-to-regexp v6
89
+ */
90
+ fullUrlFlattenString?: string;
75
91
  }
92
+ export declare type DynamicRouterInfo = Omit<RouterInfo, 'id' | 'method' | 'controllerId' | 'controllerMiddleware' | 'responseMetadata'>;
76
93
  export interface RouterPriority {
77
94
  prefix: string;
78
95
  priority: number;
@@ -88,16 +105,31 @@ export interface RouterCollectorOptions {
88
105
  includeFunctionRouter?: boolean;
89
106
  globalPrefix?: string;
90
107
  }
91
- export declare class WebRouterCollector {
92
- protected readonly baseDir: string;
108
+ export declare class MidwayWebRouterService {
109
+ readonly options: RouterCollectorOptions;
93
110
  private isReady;
94
111
  protected routes: Map<string, RouterInfo[]>;
95
- private routesPriority;
96
- protected options: RouterCollectorOptions;
97
- constructor(baseDir?: string, options?: RouterCollectorOptions);
112
+ protected routesPriority: RouterPriority[];
113
+ private cachedFlattenRouteList;
114
+ private includeCompileUrlPattern;
115
+ constructor(options?: RouterCollectorOptions);
98
116
  protected analyze(): Promise<void>;
99
- protected collectRoute(module: any, functionMeta?: boolean): void;
100
- protected collectFunctionRoute(module: any, functionMeta?: boolean): void;
117
+ protected analyzeController(): void;
118
+ protected sortPrefixAndRouter(): void;
119
+ /**
120
+ * dynamically add a controller
121
+ * @param controllerClz
122
+ * @param controllerOption
123
+ * @param functionMeta
124
+ */
125
+ addController(controllerClz: any, controllerOption: ControllerOption, functionMeta?: boolean): void;
126
+ /**
127
+ * dynamically add a route to root prefix
128
+ * @param routerPath
129
+ * @param routerFunction
130
+ * @param routerInfoOption
131
+ */
132
+ addRouter(routerFunction: (...args: any[]) => void, routerInfoOption: DynamicRouterInfo): void;
101
133
  sortRouter(urlMatchList: RouterInfo[]): {
102
134
  _pureRouter: string;
103
135
  _level: number;
@@ -107,15 +139,15 @@ export declare class WebRouterCollector {
107
139
  /**
108
140
  * uuid
109
141
  */
110
- id: string;
142
+ id?: string;
111
143
  /**
112
144
  * router prefix from controller
113
145
  */
114
- prefix: string;
146
+ prefix?: string;
115
147
  /**
116
148
  * router alias name
117
149
  */
118
- routerName: string;
150
+ routerName?: string;
119
151
  /**
120
152
  * router path, without prefix
121
153
  */
@@ -127,40 +159,43 @@ export declare class WebRouterCollector {
127
159
  /**
128
160
  * invoke function method
129
161
  */
130
- method: string;
162
+ method: string | ((...args: any[]) => void);
131
163
  /**
132
164
  * router description
133
165
  */
134
- description: string;
135
- summary: string;
166
+ description?: string;
167
+ /**
168
+ * @deprecated
169
+ */
170
+ summary?: string;
136
171
  /**
137
172
  * router handler function key,for IoC container load
138
173
  */
139
- handlerName: string;
174
+ handlerName?: string;
140
175
  /**
141
176
  * serverless func load key
142
177
  */
143
- funcHandlerName: string;
178
+ funcHandlerName?: string;
144
179
  /**
145
180
  * controller provideId
146
181
  */
147
- controllerId: string;
182
+ controllerId?: string;
148
183
  /**
149
184
  * router middleware
150
185
  */
151
- middleware: any[];
186
+ middleware?: any[];
152
187
  /**
153
188
  * controller middleware in this router
154
189
  */
155
- controllerMiddleware: any[];
190
+ controllerMiddleware?: any[];
156
191
  /**
157
192
  * request args metadata
158
193
  */
159
- requestMetadata: any[];
194
+ requestMetadata?: any[];
160
195
  /**
161
196
  * response data metadata
162
197
  */
163
- responseMetadata: any[];
198
+ responseMetadata?: any[];
164
199
  /**
165
200
  * serverless function name
166
201
  */
@@ -177,10 +212,26 @@ export declare class WebRouterCollector {
177
212
  * serverless function metadata
178
213
  */
179
214
  functionMetadata?: any;
215
+ /**
216
+ * url with prefix
217
+ */
218
+ fullUrl?: string;
219
+ /**
220
+ * pattern after path-regexp compile
221
+ */
222
+ fullUrlCompiledRegexp?: RegExp;
223
+ /**
224
+ * url after wildcard and can be path-to-regexp by path-to-regexp v6
225
+ */
226
+ fullUrlFlattenString?: string;
180
227
  }[];
181
228
  getRoutePriorityList(): Promise<RouterPriority[]>;
182
229
  getRouterTable(): Promise<Map<string, RouterInfo[]>>;
183
- getFlattenRouterTable(): Promise<RouterInfo[]>;
184
- private checkDuplicateAndPush;
230
+ getFlattenRouterTable(options?: {
231
+ compileUrlPattern?: boolean;
232
+ noCache?: boolean;
233
+ }): Promise<RouterInfo[]>;
234
+ getMatchedRouterInfo(routerUrl: string, method: string): Promise<RouterInfo | undefined>;
235
+ protected checkDuplicateAndPush(prefix: any, routerInfo: RouterInfo): void;
185
236
  }
186
- //# sourceMappingURL=webRouterCollector.d.ts.map
237
+ //# sourceMappingURL=webRouterService.d.ts.map
@@ -1,39 +1,41 @@
1
1
  "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WebRouterCollector = void 0;
12
+ exports.MidwayWebRouterService = void 0;
4
13
  const decorator_1 = require("@midwayjs/decorator");
5
14
  const util_1 = require("../util");
6
- const container_1 = require("../context/container");
7
- const fileDetector_1 = require("./fileDetector");
8
- const util = require("util");
9
15
  const error_1 = require("../error");
16
+ const util = require("util");
17
+ const pathToRegexp_1 = require("../util/pathToRegexp");
10
18
  const debug = util.debuglog('midway:debug');
11
- class WebRouterCollector {
12
- constructor(baseDir = '', options = {}) {
19
+ let MidwayWebRouterService = class MidwayWebRouterService {
20
+ constructor(options = {}) {
21
+ this.options = options;
13
22
  this.isReady = false;
14
23
  this.routes = new Map();
15
24
  this.routesPriority = [];
16
- this.baseDir = baseDir;
17
- this.options = options;
25
+ this.includeCompileUrlPattern = false;
18
26
  }
19
27
  async analyze() {
20
- if (this.baseDir) {
21
- const container = new container_1.MidwayContainer();
22
- container.setFileDetector(new fileDetector_1.DirectoryFileDetector({
23
- loadDir: this.baseDir,
24
- }));
25
- await container.ready();
26
- }
28
+ this.analyzeController();
29
+ this.sortPrefixAndRouter();
30
+ }
31
+ analyzeController() {
27
32
  const controllerModules = (0, decorator_1.listModule)(decorator_1.CONTROLLER_KEY);
28
33
  for (const module of controllerModules) {
29
- this.collectRoute(module);
30
- }
31
- if (this.options.includeFunctionRouter) {
32
- const fnModules = (0, decorator_1.listModule)(decorator_1.FUNC_KEY);
33
- for (const module of fnModules) {
34
- this.collectFunctionRoute(module);
35
- }
34
+ const controllerOption = (0, decorator_1.getClassMetadata)(decorator_1.CONTROLLER_KEY, module);
35
+ this.addController(module, controllerOption, this.options.includeFunctionRouter);
36
36
  }
37
+ }
38
+ sortPrefixAndRouter() {
37
39
  // filter empty prefix
38
40
  this.routesPriority = this.routesPriority.filter(item => {
39
41
  const prefixList = this.routes.get(item.prefix);
@@ -55,12 +57,17 @@ class WebRouterCollector {
55
57
  return routeB.prefix.length - routeA.prefix.length;
56
58
  });
57
59
  }
58
- collectRoute(module, functionMeta = false) {
60
+ /**
61
+ * dynamically add a controller
62
+ * @param controllerClz
63
+ * @param controllerOption
64
+ * @param functionMeta
65
+ */
66
+ addController(controllerClz, controllerOption, functionMeta = false) {
59
67
  var _a;
60
- const controllerId = (0, decorator_1.getProviderName)(module);
68
+ const controllerId = (0, decorator_1.getProviderName)(controllerClz);
61
69
  debug(`[core]: Found Controller ${controllerId}.`);
62
- const id = (0, decorator_1.getProviderUUId)(module);
63
- const controllerOption = (0, decorator_1.getClassMetadata)(decorator_1.CONTROLLER_KEY, module);
70
+ const id = (0, decorator_1.getProviderUUId)(controllerClz);
64
71
  let priority;
65
72
  // implement middleware in controller
66
73
  const middleware = controllerOption.routerOptions.middleware;
@@ -83,9 +90,18 @@ class WebRouterCollector {
83
90
  middleware,
84
91
  routerOptions: controllerOption.routerOptions,
85
92
  controllerId,
86
- routerModule: module,
93
+ routerModule: controllerClz,
87
94
  });
88
95
  }
96
+ else {
97
+ // 不同的 controller,可能会有相同的 prefix,一旦 options 不同,就要报错
98
+ if (middleware) {
99
+ const originRoute = this.routesPriority.filter(el => {
100
+ return el.prefix === prefix;
101
+ })[0];
102
+ throw new error_1.MidwayDuplicateControllerOptionsError(prefix, controllerId, originRoute.controllerId);
103
+ }
104
+ }
89
105
  // set ignorePrefix
90
106
  if (!this.routes.has(ignorePrefix)) {
91
107
  this.routes.set(ignorePrefix, []);
@@ -95,14 +111,14 @@ class WebRouterCollector {
95
111
  middleware,
96
112
  routerOptions: controllerOption.routerOptions,
97
113
  controllerId,
98
- routerModule: module,
114
+ routerModule: controllerClz,
99
115
  });
100
116
  }
101
- const webRouterInfo = (0, decorator_1.getClassMetadata)(decorator_1.WEB_ROUTER_KEY, module);
117
+ const webRouterInfo = (0, decorator_1.getClassMetadata)(decorator_1.WEB_ROUTER_KEY, controllerClz);
102
118
  if (webRouterInfo && typeof webRouterInfo[Symbol.iterator] === 'function') {
103
119
  for (const webRouter of webRouterInfo) {
104
- const routeArgsInfo = (0, decorator_1.getPropertyDataFromClass)(decorator_1.WEB_ROUTER_PARAM_KEY, module, webRouter.method) || [];
105
- const routerResponseData = (0, decorator_1.getPropertyMetadata)(decorator_1.WEB_RESPONSE_KEY, module, webRouter.method) || [];
120
+ const routeArgsInfo = (0, decorator_1.getPropertyDataFromClass)(decorator_1.WEB_ROUTER_PARAM_KEY, controllerClz, webRouter.method) || [];
121
+ const routerResponseData = (0, decorator_1.getPropertyMetadata)(decorator_1.WEB_RESPONSE_KEY, controllerClz, webRouter.method) || [];
106
122
  const data = {
107
123
  id,
108
124
  prefix: webRouter.ignoreGlobalPrefix ? ignorePrefix : prefix,
@@ -136,92 +152,29 @@ class WebRouterCollector {
136
152
  }
137
153
  }
138
154
  }
139
- collectFunctionRoute(module, functionMeta = false) {
140
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
141
- // serverlessTrigger metadata
142
- const webRouterInfo = (0, decorator_1.getClassMetadata)(decorator_1.FUNC_KEY, module);
143
- const controllerId = (0, decorator_1.getProviderName)(module);
144
- const id = (0, decorator_1.getProviderUUId)(module);
145
- const prefix = '/';
155
+ /**
156
+ * dynamically add a route to root prefix
157
+ * @param routerPath
158
+ * @param routerFunction
159
+ * @param routerInfoOption
160
+ */
161
+ addRouter(routerFunction, routerInfoOption) {
162
+ const prefix = routerInfoOption.prefix || '';
163
+ routerInfoOption.requestMethod = (routerInfoOption.requestMethod || 'GET').toUpperCase();
146
164
  if (!this.routes.has(prefix)) {
147
165
  this.routes.set(prefix, []);
148
166
  this.routesPriority.push({
149
167
  prefix,
150
- priority: -999,
168
+ priority: 0,
151
169
  middleware: [],
152
170
  routerOptions: {},
153
- controllerId,
154
- routerModule: module,
171
+ controllerId: undefined,
172
+ routerModule: undefined,
155
173
  });
156
174
  }
157
- for (const webRouter of webRouterInfo) {
158
- // 新的 @ServerlessTrigger 写法
159
- if ((_a = webRouter['metadata']) === null || _a === void 0 ? void 0 : _a['path']) {
160
- const routeArgsInfo = (0, decorator_1.getPropertyDataFromClass)(decorator_1.WEB_ROUTER_PARAM_KEY, module, webRouter['methodName']) || [];
161
- const routerResponseData = (0, decorator_1.getPropertyMetadata)(decorator_1.WEB_RESPONSE_KEY, module, webRouter['methodName']) || [];
162
- // 新 http/api gateway 函数
163
- const data = {
164
- id,
165
- prefix,
166
- routerName: '',
167
- url: webRouter['metadata']['path'],
168
- requestMethod: (_c = (_b = webRouter['metadata']) === null || _b === void 0 ? void 0 : _b['method']) !== null && _c !== void 0 ? _c : 'get',
169
- method: webRouter['methodName'],
170
- description: '',
171
- summary: '',
172
- handlerName: `${controllerId}.${webRouter['methodName']}`,
173
- funcHandlerName: `${controllerId}.${webRouter['methodName']}`,
174
- controllerId,
175
- middleware: ((_d = webRouter['metadata']) === null || _d === void 0 ? void 0 : _d['middleware']) || [],
176
- controllerMiddleware: [],
177
- requestMetadata: routeArgsInfo,
178
- responseMetadata: routerResponseData,
179
- };
180
- if (functionMeta) {
181
- const functionMeta = (0, decorator_1.getPropertyMetadata)(decorator_1.SERVERLESS_FUNC_KEY, module, webRouter['methodName']) || {};
182
- const functionName = (_f = (_e = functionMeta['functionName']) !== null && _e !== void 0 ? _e : webRouter['functionName']) !== null && _f !== void 0 ? _f : createFunctionName(module, webRouter['methodName']);
183
- data.functionName = functionName;
184
- data.functionTriggerName = webRouter['type'];
185
- data.functionTriggerMetadata = webRouter['metadata'];
186
- data.functionMetadata = {
187
- functionName,
188
- ...functionMeta,
189
- };
190
- }
191
- this.checkDuplicateAndPush(prefix, data);
192
- }
193
- else {
194
- if (functionMeta) {
195
- const functionMeta = (0, decorator_1.getPropertyMetadata)(decorator_1.SERVERLESS_FUNC_KEY, module, webRouter['methodName']) || {};
196
- const functionName = (_h = (_g = functionMeta['functionName']) !== null && _g !== void 0 ? _g : webRouter['functionName']) !== null && _h !== void 0 ? _h : createFunctionName(module, webRouter['methodName']);
197
- // 其他类型的函数
198
- this.checkDuplicateAndPush(prefix, {
199
- id,
200
- prefix,
201
- routerName: '',
202
- url: '',
203
- requestMethod: '',
204
- method: webRouter['methodName'],
205
- description: '',
206
- summary: '',
207
- handlerName: `${controllerId}.${webRouter['methodName']}`,
208
- funcHandlerName: `${controllerId}.${webRouter['methodName']}`,
209
- controllerId,
210
- middleware: ((_j = webRouter['metadata']) === null || _j === void 0 ? void 0 : _j['middleware']) || [],
211
- controllerMiddleware: [],
212
- requestMetadata: [],
213
- responseMetadata: [],
214
- functionName,
215
- functionTriggerName: webRouter['type'],
216
- functionTriggerMetadata: webRouter['metadata'],
217
- functionMetadata: {
218
- functionName,
219
- ...functionMeta,
220
- },
221
- });
222
- }
223
- }
224
- }
175
+ this.checkDuplicateAndPush(prefix, Object.assign(routerInfoOption, {
176
+ method: routerFunction,
177
+ }));
225
178
  }
226
179
  sortRouter(urlMatchList) {
227
180
  // 1. 绝对路径规则优先级最高如 /ab/cb/e
@@ -299,7 +252,19 @@ class WebRouterCollector {
299
252
  }
300
253
  return this.routes;
301
254
  }
302
- async getFlattenRouterTable() {
255
+ async getFlattenRouterTable(options = {}) {
256
+ if (this.cachedFlattenRouteList && !options.noCache) {
257
+ if (options.compileUrlPattern && !this.includeCompileUrlPattern) {
258
+ this.includeCompileUrlPattern = true;
259
+ // attach match pattern function
260
+ for (const item of this.cachedFlattenRouteList) {
261
+ if (item.fullUrlFlattenString) {
262
+ item.fullUrlCompiledRegexp = pathToRegexp_1.PathToRegexpUtil.toRegexp(item.fullUrlFlattenString);
263
+ }
264
+ }
265
+ }
266
+ return this.cachedFlattenRouteList;
267
+ }
303
268
  if (!this.isReady) {
304
269
  await this.analyze();
305
270
  this.isReady = true;
@@ -308,8 +273,34 @@ class WebRouterCollector {
308
273
  for (const routerPriority of this.routesPriority) {
309
274
  routeArr = routeArr.concat(this.routes.get(routerPriority.prefix));
310
275
  }
276
+ if (options.compileUrlPattern) {
277
+ this.includeCompileUrlPattern = true;
278
+ // attach match pattern function
279
+ for (const item of routeArr) {
280
+ if (item.fullUrlFlattenString) {
281
+ item.fullUrlCompiledRegexp = pathToRegexp_1.PathToRegexpUtil.toRegexp(item.fullUrlFlattenString);
282
+ }
283
+ }
284
+ }
285
+ this.cachedFlattenRouteList = routeArr;
311
286
  return routeArr;
312
287
  }
288
+ async getMatchedRouterInfo(routerUrl, method) {
289
+ const routes = await this.getFlattenRouterTable({
290
+ compileUrlPattern: true,
291
+ });
292
+ let matchedRouterInfo;
293
+ for (const item of routes) {
294
+ if (item.fullUrlCompiledRegexp) {
295
+ if (method.toUpperCase() === item['requestMethod'].toUpperCase() &&
296
+ item.fullUrlCompiledRegexp.test(routerUrl)) {
297
+ matchedRouterInfo = item;
298
+ break;
299
+ }
300
+ }
301
+ }
302
+ return matchedRouterInfo;
303
+ }
313
304
  checkDuplicateAndPush(prefix, routerInfo) {
314
305
  const prefixList = this.routes.get(prefix);
315
306
  const matched = prefixList.filter(item => {
@@ -321,11 +312,25 @@ class WebRouterCollector {
321
312
  if (matched && matched.length) {
322
313
  throw new error_1.MidwayDuplicateRouteError(`${routerInfo.requestMethod} ${routerInfo.url}`, `${matched[0].handlerName}`, `${routerInfo.handlerName}`);
323
314
  }
315
+ // format url
316
+ if (!routerInfo.fullUrlFlattenString &&
317
+ routerInfo.url &&
318
+ typeof routerInfo.url === 'string') {
319
+ routerInfo.fullUrl = (0, util_1.joinURLPath)(prefix, routerInfo.url);
320
+ if (/\*$/.test(routerInfo.fullUrl)) {
321
+ routerInfo.fullUrlFlattenString = routerInfo.fullUrl.replace('*', '(.*)');
322
+ }
323
+ else {
324
+ routerInfo.fullUrlFlattenString = routerInfo.fullUrl;
325
+ }
326
+ }
324
327
  prefixList.push(routerInfo);
325
328
  }
326
- }
327
- exports.WebRouterCollector = WebRouterCollector;
328
- function createFunctionName(target, functionName) {
329
- return (0, decorator_1.getProviderName)(target).replace(/[:#]/g, '-') + '-' + functionName;
330
- }
331
- //# sourceMappingURL=webRouterCollector.js.map
329
+ };
330
+ MidwayWebRouterService = __decorate([
331
+ (0, decorator_1.Provide)(),
332
+ (0, decorator_1.Scope)(decorator_1.ScopeEnum.Singleton),
333
+ __metadata("design:paramtypes", [Object])
334
+ ], MidwayWebRouterService);
335
+ exports.MidwayWebRouterService = MidwayWebRouterService;
336
+ //# sourceMappingURL=webRouterService.js.map
package/dist/setup.js CHANGED
@@ -7,6 +7,7 @@ const decorator_1 = require("@midwayjs/decorator");
7
7
  const util = require("util");
8
8
  const path_1 = require("path");
9
9
  const logger_1 = require("@midwayjs/logger");
10
+ const slsFunctionService_1 = require("./service/slsFunctionService");
10
11
  const debug = util.debuglog('midway:debug');
11
12
  /**
12
13
  * midway framework main entry, this method bootstrap all service and framework.
@@ -95,6 +96,8 @@ function prepareGlobalApplicationContext(globalOptions) {
95
96
  applicationContext.bindClass(_1.MidwayMiddlewareService);
96
97
  applicationContext.bindClass(_1.MidwayLifeCycleService);
97
98
  applicationContext.bindClass(_1.MidwayMockService);
99
+ applicationContext.bindClass(_1.MidwayWebRouterService);
100
+ applicationContext.bindClass(slsFunctionService_1.MidwayServerlessFunctionService);
98
101
  // bind preload module
99
102
  if (globalOptions.preloadModules && globalOptions.preloadModules.length) {
100
103
  for (const preloadModule of globalOptions.preloadModules) {
@@ -1,5 +1,7 @@
1
1
  import { IConfigurationOptions, IMidwayContainer, IMidwayFramework } from '../interface';
2
+ import { AsyncContextManager } from '../common/asyncContextManager';
2
3
  export declare const getCurrentApplicationContext: () => IMidwayContainer;
3
4
  export declare const getCurrentMainFramework: <APP extends import("../interface").IMidwayBaseApplication<CTX>, CTX extends import("../interface").Context, CONFIG extends IConfigurationOptions>() => IMidwayFramework<APP, CTX, CONFIG, unknown, unknown>;
4
5
  export declare const getCurrentMainApp: <APP extends import("../interface").IMidwayBaseApplication<import("../interface").Context>>() => APP;
6
+ export declare const getCurrentAsyncContextManager: () => AsyncContextManager;
5
7
  //# sourceMappingURL=contextUtil.d.ts.map
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getCurrentMainApp = exports.getCurrentMainFramework = exports.getCurrentApplicationContext = void 0;
3
+ exports.getCurrentAsyncContextManager = exports.getCurrentMainApp = exports.getCurrentMainFramework = exports.getCurrentApplicationContext = void 0;
4
+ const interface_1 = require("../interface");
4
5
  const getCurrentApplicationContext = () => {
5
6
  return global['MIDWAY_APPLICATION_CONTEXT'];
6
7
  };
@@ -17,4 +18,8 @@ const getCurrentMainApp = () => {
17
18
  return undefined;
18
19
  };
19
20
  exports.getCurrentMainApp = getCurrentMainApp;
21
+ const getCurrentAsyncContextManager = () => {
22
+ return (0, exports.getCurrentApplicationContext)().get(interface_1.ASYNC_CONTEXT_MANAGER_KEY);
23
+ };
24
+ exports.getCurrentAsyncContextManager = getCurrentAsyncContextManager;
20
25
  //# sourceMappingURL=contextUtil.js.map
@@ -90,4 +90,5 @@ export declare function pathMatching(options: any): (ctx?: any) => any;
90
90
  */
91
91
  export declare function wrapMiddleware(mw: FunctionMiddleware<any, any>, options: any): (context: any, next: any, options?: any) => any;
92
92
  export declare function isIncludeProperty(obj: any, prop: string): boolean;
93
+ export declare function wrapAsync(handler: any): (...args: any[]) => any;
93
94
  //# sourceMappingURL=index.d.ts.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isIncludeProperty = exports.wrapMiddleware = exports.pathMatching = exports.toPathMatch = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.getCurrentDateString = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetPrototypeMethod = exports.joinURLPath = exports.getUserHome = exports.parsePrefix = exports.safelyGet = exports.safeRequire = exports.getCurrentEnvironment = exports.isDevelopmentEnvironment = void 0;
3
+ exports.wrapAsync = exports.isIncludeProperty = exports.wrapMiddleware = exports.pathMatching = exports.toPathMatch = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.getCurrentDateString = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetPrototypeMethod = exports.joinURLPath = exports.getUserHome = exports.parsePrefix = exports.safelyGet = exports.safeRequire = exports.getCurrentEnvironment = exports.isDevelopmentEnvironment = void 0;
4
4
  const path_1 = require("path");
5
5
  const fs_1 = require("fs");
6
6
  const util_1 = require("util");
@@ -238,7 +238,7 @@ function toPathMatch(pattern) {
238
238
  return ctx => pattern;
239
239
  }
240
240
  if (typeof pattern === 'string') {
241
- const reg = (0, pathToRegexp_1.pathToRegexp)(pattern, [], { end: false });
241
+ const reg = pathToRegexp_1.PathToRegexpUtil.toRegexp(pattern.replace('*', '(.*)'));
242
242
  if (reg.global)
243
243
  reg.lastIndex = 0;
244
244
  return ctx => reg.test(ctx.path);
@@ -313,4 +313,25 @@ function isIncludeProperty(obj, prop) {
313
313
  return false;
314
314
  }
315
315
  exports.isIncludeProperty = isIncludeProperty;
316
+ function wrapAsync(handler) {
317
+ return (...args) => {
318
+ if (typeof args[args.length - 1] === 'function') {
319
+ const callback = args.pop();
320
+ if (handler.constructor.name !== 'AsyncFunction') {
321
+ const err = new TypeError('Must be an AsyncFunction');
322
+ return callback(err);
323
+ }
324
+ // 其他事件场景
325
+ return handler.apply(handler, args).then(result => {
326
+ callback(null, result);
327
+ }, err => {
328
+ callback(err);
329
+ });
330
+ }
331
+ else {
332
+ return handler.apply(handler, args);
333
+ }
334
+ };
335
+ }
336
+ exports.wrapAsync = wrapAsync;
316
337
  //# sourceMappingURL=index.js.map