@midwayjs/core 3.3.6 → 3.4.0-beta.3

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.
@@ -1,37 +1,40 @@
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.WebRouterCollector = 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 contextUtil_1 = require("../util/contextUtil");
18
+ const container_1 = require("../context/container");
19
+ const fileDetector_1 = require("../common/fileDetector");
10
20
  const debug = util.debuglog('midway:debug');
11
- class WebRouterCollector {
12
- constructor(baseDir = '', options = {}) {
21
+ let MidwayWebRouterService = class MidwayWebRouterService {
22
+ constructor(options = {}) {
23
+ this.options = options;
13
24
  this.isReady = false;
14
25
  this.routes = new Map();
15
26
  this.routesPriority = [];
16
- this.baseDir = baseDir;
17
- this.options = options;
18
27
  }
19
28
  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
- }
27
29
  const controllerModules = (0, decorator_1.listModule)(decorator_1.CONTROLLER_KEY);
28
30
  for (const module of controllerModules) {
29
- this.collectRoute(module);
31
+ const controllerOption = (0, decorator_1.getClassMetadata)(decorator_1.CONTROLLER_KEY, module);
32
+ this.addController(module, controllerOption, this.options.includeFunctionRouter);
30
33
  }
31
34
  if (this.options.includeFunctionRouter) {
32
35
  const fnModules = (0, decorator_1.listModule)(decorator_1.FUNC_KEY);
33
36
  for (const module of fnModules) {
34
- this.collectFunctionRoute(module);
37
+ this.collectFunctionRoute(module, this.options.includeFunctionRouter);
35
38
  }
36
39
  }
37
40
  // filter empty prefix
@@ -54,13 +57,37 @@ class WebRouterCollector {
54
57
  this.routesPriority = this.routesPriority.sort((routeA, routeB) => {
55
58
  return routeB.prefix.length - routeA.prefix.length;
56
59
  });
60
+ // format function router meta
61
+ if (this.options.includeFunctionRouter) {
62
+ // requestMethod all transform to other method
63
+ for (const routerInfo of this.routes.values()) {
64
+ for (const info of routerInfo) {
65
+ if (info.requestMethod === 'all') {
66
+ info.functionTriggerMetadata.method = [
67
+ 'get',
68
+ 'post',
69
+ 'put',
70
+ 'delete',
71
+ 'head',
72
+ 'patch',
73
+ 'options',
74
+ ];
75
+ }
76
+ }
77
+ }
78
+ }
57
79
  }
58
- collectRoute(module, functionMeta = false) {
80
+ /**
81
+ * dynamically add a controller
82
+ * @param controllerClz
83
+ * @param controllerOption
84
+ * @param functionMeta
85
+ */
86
+ addController(controllerClz, controllerOption, functionMeta = false) {
59
87
  var _a;
60
- const controllerId = (0, decorator_1.getProviderName)(module);
88
+ const controllerId = (0, decorator_1.getProviderName)(controllerClz);
61
89
  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);
90
+ const id = (0, decorator_1.getProviderUUId)(controllerClz);
64
91
  let priority;
65
92
  // implement middleware in controller
66
93
  const middleware = controllerOption.routerOptions.middleware;
@@ -83,9 +110,18 @@ class WebRouterCollector {
83
110
  middleware,
84
111
  routerOptions: controllerOption.routerOptions,
85
112
  controllerId,
86
- routerModule: module,
113
+ routerModule: controllerClz,
87
114
  });
88
115
  }
116
+ else {
117
+ // 不同的 controller,可能会有相同的 prefix,一旦 options 不同,就要报错
118
+ if (middleware) {
119
+ const originRoute = this.routesPriority.filter(el => {
120
+ return el.prefix === prefix;
121
+ })[0];
122
+ throw new error_1.MidwayDuplicateControllerOptionsError(prefix, controllerId, originRoute.controllerId);
123
+ }
124
+ }
89
125
  // set ignorePrefix
90
126
  if (!this.routes.has(ignorePrefix)) {
91
127
  this.routes.set(ignorePrefix, []);
@@ -95,14 +131,14 @@ class WebRouterCollector {
95
131
  middleware,
96
132
  routerOptions: controllerOption.routerOptions,
97
133
  controllerId,
98
- routerModule: module,
134
+ routerModule: controllerClz,
99
135
  });
100
136
  }
101
- const webRouterInfo = (0, decorator_1.getClassMetadata)(decorator_1.WEB_ROUTER_KEY, module);
137
+ const webRouterInfo = (0, decorator_1.getClassMetadata)(decorator_1.WEB_ROUTER_KEY, controllerClz);
102
138
  if (webRouterInfo && typeof webRouterInfo[Symbol.iterator] === 'function') {
103
139
  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) || [];
140
+ const routeArgsInfo = (0, decorator_1.getPropertyDataFromClass)(decorator_1.WEB_ROUTER_PARAM_KEY, controllerClz, webRouter.method) || [];
141
+ const routerResponseData = (0, decorator_1.getPropertyMetadata)(decorator_1.WEB_RESPONSE_KEY, controllerClz, webRouter.method) || [];
106
142
  const data = {
107
143
  id,
108
144
  prefix: webRouter.ignoreGlobalPrefix ? ignorePrefix : prefix,
@@ -136,6 +172,18 @@ class WebRouterCollector {
136
172
  }
137
173
  }
138
174
  }
175
+ /**
176
+ * dynamically add a route to root prefix
177
+ * @param routerPath
178
+ * @param routerFunction
179
+ * @param routerInfoOption
180
+ */
181
+ addRouter(routerPath, routerFunction, routerInfoOption) {
182
+ this.checkDuplicateAndPush('/', Object.assign(routerInfoOption, {
183
+ method: routerFunction,
184
+ url: routerPath,
185
+ }));
186
+ }
139
187
  collectFunctionRoute(module, functionMeta = false) {
140
188
  var _a, _b, _c, _d, _e, _f, _g, _h, _j;
141
189
  // serverlessTrigger metadata
@@ -323,9 +371,56 @@ class WebRouterCollector {
323
371
  }
324
372
  prefixList.push(routerInfo);
325
373
  }
326
- }
327
- exports.WebRouterCollector = WebRouterCollector;
374
+ };
375
+ MidwayWebRouterService = __decorate([
376
+ (0, decorator_1.Provide)(),
377
+ (0, decorator_1.Scope)(decorator_1.ScopeEnum.Singleton),
378
+ __metadata("design:paramtypes", [Object])
379
+ ], MidwayWebRouterService);
380
+ exports.MidwayWebRouterService = MidwayWebRouterService;
328
381
  function createFunctionName(target, functionName) {
329
382
  return (0, decorator_1.getProviderName)(target).replace(/[:#]/g, '-') + '-' + functionName;
330
383
  }
331
- //# sourceMappingURL=webRouterCollector.js.map
384
+ /**
385
+ * @deprecated use built-in MidwayWebRouterService first
386
+ */
387
+ class WebRouterCollector {
388
+ constructor(baseDir = '', options = {}) {
389
+ this.baseDir = baseDir;
390
+ this.options = options;
391
+ }
392
+ async init() {
393
+ if (!this.proxy) {
394
+ if (this.baseDir) {
395
+ const container = new container_1.MidwayContainer();
396
+ (0, decorator_1.bindContainer)(container);
397
+ container.setFileDetector(new fileDetector_1.DirectoryFileDetector({
398
+ loadDir: this.baseDir,
399
+ }));
400
+ await container.ready();
401
+ }
402
+ if ((0, contextUtil_1.getCurrentMainFramework)()) {
403
+ this.proxy = await (0, contextUtil_1.getCurrentMainFramework)()
404
+ .getApplicationContext()
405
+ .getAsync(MidwayWebRouterService, [this.options]);
406
+ }
407
+ else {
408
+ this.proxy = new MidwayWebRouterService(this.options);
409
+ }
410
+ }
411
+ }
412
+ async getRoutePriorityList() {
413
+ await this.init();
414
+ return this.proxy.getRoutePriorityList();
415
+ }
416
+ async getRouterTable() {
417
+ await this.init();
418
+ return this.proxy.getRouterTable();
419
+ }
420
+ async getFlattenRouterTable() {
421
+ await this.init();
422
+ return this.proxy.getFlattenRouterTable();
423
+ }
424
+ }
425
+ exports.WebRouterCollector = WebRouterCollector;
426
+ //# sourceMappingURL=webRouterService.js.map
package/dist/setup.js CHANGED
@@ -95,6 +95,7 @@ function prepareGlobalApplicationContext(globalOptions) {
95
95
  applicationContext.bindClass(_1.MidwayMiddlewareService);
96
96
  applicationContext.bindClass(_1.MidwayLifeCycleService);
97
97
  applicationContext.bindClass(_1.MidwayMockService);
98
+ applicationContext.bindClass(_1.MidwayWebRouterService);
98
99
  // bind preload module
99
100
  if (globalOptions.preloadModules && globalOptions.preloadModules.length) {
100
101
  for (const preloadModule of globalOptions.preloadModules) {
@@ -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");
@@ -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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/core",
3
- "version": "3.3.6",
3
+ "version": "3.4.0-beta.3",
4
4
  "description": "midway core",
5
5
  "main": "dist/index",
6
6
  "typings": "dist/index.d.ts",
@@ -21,7 +21,7 @@
21
21
  ],
22
22
  "license": "MIT",
23
23
  "devDependencies": {
24
- "@midwayjs/decorator": "^3.3.4",
24
+ "@midwayjs/decorator": "^3.4.0-beta.3",
25
25
  "koa": "2.13.4",
26
26
  "midway-test-component": "*",
27
27
  "mm": "3.2.0",
@@ -45,5 +45,5 @@
45
45
  "engines": {
46
46
  "node": ">=12"
47
47
  },
48
- "gitHead": "a603d2348d6141f8f723901498f03a162a037708"
48
+ "gitHead": "ddbff5c3da5d908953cc691a8e5de4f0197de365"
49
49
  }