@midwayjs/core 3.4.0-beta.1 → 3.4.0-beta.4

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,7 +1,8 @@
1
1
  export declare abstract class DataSourceManager<T> {
2
2
  protected dataSource: Map<string, T>;
3
3
  protected options: {};
4
- protected initDataSource(options?: any): Promise<void>;
4
+ protected modelMapping: WeakMap<object, any>;
5
+ protected initDataSource(options: any, appDir: string): Promise<void>;
5
6
  /**
6
7
  * get a data source instance
7
8
  * @param dataSourceName
@@ -19,10 +20,16 @@ export declare abstract class DataSourceManager<T> {
19
20
  */
20
21
  isConnected(dataSourceName: string): Promise<boolean>;
21
22
  createInstance(config: any, clientName: any): Promise<T | void>;
23
+ /**
24
+ * get data source name by model or repository
25
+ * @param modelOrRepository
26
+ */
27
+ getDataSourceNameByModel(modelOrRepository: any): string | undefined;
22
28
  abstract getName(): string;
23
29
  protected abstract createDataSource(config: any, dataSourceName: string): Promise<T | void> | (T | void);
24
30
  protected abstract checkConnected(dataSource: T): Promise<boolean>;
25
31
  protected destroyDataSource(dataSource: T): Promise<void>;
26
32
  stop(): Promise<void>;
27
33
  }
34
+ export declare function globModels(globString: string, appDir: string): any[];
28
35
  //# sourceMappingURL=dataSourceManager.d.ts.map
@@ -1,22 +1,48 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DataSourceManager = void 0;
3
+ exports.globModels = exports.DataSourceManager = void 0;
4
4
  /**
5
5
  * 数据源管理器实现
6
6
  */
7
7
  const extend_1 = require("../util/extend");
8
8
  const error_1 = require("../error");
9
+ const glob_1 = require("@midwayjs/glob");
10
+ const path_1 = require("path");
11
+ const decorator_1 = require("@midwayjs/decorator");
12
+ const DEFAULT_PATTERN = ['**/**.ts', '**/**.js'];
9
13
  class DataSourceManager {
10
14
  constructor() {
11
15
  this.dataSource = new Map();
12
16
  this.options = {};
17
+ this.modelMapping = new WeakMap();
13
18
  }
14
- async initDataSource(options = {}) {
19
+ async initDataSource(options, appDir) {
15
20
  this.options = options;
16
21
  if (options.dataSource) {
17
22
  for (const dataSourceName in options.dataSource) {
23
+ const dataSourceOptions = options.dataSource[dataSourceName];
24
+ if (dataSourceOptions['entities']) {
25
+ const entities = new Set();
26
+ // loop entities and glob files to model
27
+ for (const entity of dataSourceOptions['entities']) {
28
+ if (typeof entity === 'string') {
29
+ // string will be glob file
30
+ const models = globModels(entity, appDir);
31
+ for (const model of models) {
32
+ entities.add(model);
33
+ this.modelMapping.set(model, dataSourceName);
34
+ }
35
+ }
36
+ else {
37
+ // model will be add to array
38
+ entities.add(entity);
39
+ this.modelMapping.set(entity, dataSourceName);
40
+ }
41
+ }
42
+ dataSourceOptions['entities'] = Array.from(entities);
43
+ }
18
44
  // create data source
19
- await this.createInstance(options.dataSource[dataSourceName], dataSourceName);
45
+ await this.createInstance(dataSourceOptions, dataSourceName);
20
46
  }
21
47
  }
22
48
  else {
@@ -58,12 +84,44 @@ class DataSourceManager {
58
84
  return client;
59
85
  }
60
86
  }
87
+ /**
88
+ * get data source name by model or repository
89
+ * @param modelOrRepository
90
+ */
91
+ getDataSourceNameByModel(modelOrRepository) {
92
+ return this.modelMapping.get(modelOrRepository);
93
+ }
61
94
  async destroyDataSource(dataSource) { }
62
95
  async stop() {
63
96
  for (const value of this.dataSource.values()) {
64
97
  await this.destroyDataSource(value);
65
98
  }
99
+ this.dataSource.clear();
66
100
  }
67
101
  }
68
102
  exports.DataSourceManager = DataSourceManager;
103
+ function globModels(globString, appDir) {
104
+ const cwd = (0, path_1.join)(appDir, globString);
105
+ const models = [];
106
+ // string will be glob file
107
+ const files = (0, glob_1.run)(DEFAULT_PATTERN, {
108
+ cwd,
109
+ });
110
+ for (const file of files) {
111
+ const exports = require(file);
112
+ if (decorator_1.Types.isClass(exports)) {
113
+ models.push(exports);
114
+ }
115
+ else {
116
+ for (const m in exports) {
117
+ const module = exports[m];
118
+ if (decorator_1.Types.isClass(module)) {
119
+ models.push(module);
120
+ }
121
+ }
122
+ }
123
+ }
124
+ return models;
125
+ }
126
+ exports.globModels = globModels;
69
127
  //# sourceMappingURL=dataSourceManager.js.map
@@ -1,15 +1,16 @@
1
- import { RouterInfo, IMidwayApplication } from '../index';
1
+ import { MidwayWebRouterService, RouterInfo, IMidwayApplication } from '../index';
2
2
  export declare abstract class WebControllerGenerator<Router extends {
3
3
  use: (...args: any[]) => void;
4
4
  }> {
5
5
  readonly app: IMidwayApplication;
6
- protected constructor(app: IMidwayApplication);
6
+ readonly midwayWebRouterService: MidwayWebRouterService;
7
+ protected constructor(app: IMidwayApplication, midwayWebRouterService: MidwayWebRouterService);
7
8
  /**
8
9
  * wrap controller string to middleware function
9
10
  * @param routeInfo
10
11
  */
11
12
  generateKoaController(routeInfo: RouterInfo): (ctx: any, next: any) => Promise<void>;
12
- loadMidwayController(globalPrefix: string, routerHandler?: (newRouter: Router) => void): Promise<void>;
13
+ loadMidwayController(routerHandler?: (newRouter: Router) => void): Promise<void>;
13
14
  abstract createRouter(routerOptions: any): Router;
14
15
  abstract generateController(routeInfo: RouterInfo): any;
15
16
  }
@@ -12,8 +12,9 @@ const index_1 = require("../index");
12
12
  const util = require("util");
13
13
  const debug = util.debuglog('midway:debug');
14
14
  class WebControllerGenerator {
15
- constructor(app) {
15
+ constructor(app, midwayWebRouterService) {
16
16
  this.app = app;
17
+ this.midwayWebRouterService = midwayWebRouterService;
17
18
  }
18
19
  /**
19
20
  * wrap controller string to middleware function
@@ -22,14 +23,24 @@ class WebControllerGenerator {
22
23
  generateKoaController(routeInfo) {
23
24
  return async (ctx, next) => {
24
25
  const args = [ctx, next];
25
- const controller = await ctx.requestContext.getAsync(routeInfo.id);
26
- // eslint-disable-next-line prefer-spread
27
- const result = await controller[routeInfo.method].apply(controller, args);
28
- if (result !== undefined) {
29
- ctx.body = result;
26
+ let result;
27
+ if (typeof routeInfo.method !== 'string') {
28
+ result = await routeInfo.method(ctx, next);
29
+ }
30
+ else {
31
+ const controller = await ctx.requestContext.getAsync(routeInfo.id);
32
+ // eslint-disable-next-line prefer-spread
33
+ result = await controller[routeInfo.method].apply(controller, args);
30
34
  }
31
- if (ctx.body === undefined && !ctx.response._explicitStatus) {
32
- ctx.body = undefined;
35
+ if (result !== undefined) {
36
+ if (result === null) {
37
+ // 这样设置可以绕过 koa 的 _explicitStatus 赋值机制
38
+ ctx.response._body = null;
39
+ ctx.response._midwayControllerNullBody = true;
40
+ }
41
+ else {
42
+ ctx.body = result;
43
+ }
33
44
  }
34
45
  // implement response decorator
35
46
  if (Array.isArray(routeInfo.responseMetadata) &&
@@ -56,13 +67,10 @@ class WebControllerGenerator {
56
67
  }
57
68
  };
58
69
  }
59
- async loadMidwayController(globalPrefix, routerHandler) {
70
+ async loadMidwayController(routerHandler) {
60
71
  var _a, _b;
61
- const collector = new index_1.WebRouterCollector('', {
62
- globalPrefix,
63
- });
64
- const routerTable = await collector.getRouterTable();
65
- const routerList = await collector.getRoutePriorityList();
72
+ const routerTable = await this.midwayWebRouterService.getRouterTable();
73
+ const routerList = await this.midwayWebRouterService.getRoutePriorityList();
66
74
  const applicationContext = this.app.getApplicationContext();
67
75
  const logger = this.app.getCoreLogger();
68
76
  const middlewareService = applicationContext.get(index_1.MidwayMiddlewareService);
@@ -17,6 +17,7 @@ export declare const FrameworkErrorEnum: {
17
17
  readonly INCONSISTENT_VERSION: "MIDWAY_10013";
18
18
  readonly INVALID_CONFIG: "MIDWAY_10014";
19
19
  readonly DUPLICATE_CLASS_NAME: "MIDWAY_10015";
20
+ readonly DUPLICATE_CONTROLLER_PREFIX_OPTIONS: "MIDWAY_10016";
20
21
  };
21
22
  export declare class MidwayCommonError extends MidwayError {
22
23
  constructor(message: string);
@@ -66,4 +67,7 @@ export declare class MidwayInconsistentVersionError extends MidwayError {
66
67
  export declare class MidwayDuplicateClassNameError extends MidwayError {
67
68
  constructor(className: string, existPath: string, existPathOther: string);
68
69
  }
70
+ export declare class MidwayDuplicateControllerOptionsError extends MidwayError {
71
+ constructor(prefix: string, existController: string, existControllerOther: string);
72
+ }
69
73
  //# sourceMappingURL=framework.d.ts.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MidwayDuplicateClassNameError = exports.MidwayInconsistentVersionError = exports.MidwayUtilHttpClientTimeoutError = exports.MidwayMissingImportComponentError = exports.MidwaySingletonInjectRequestError = exports.MidwayUseWrongMethodError = exports.MidwayDuplicateRouteError = exports.MidwayResolverMissingError = exports.MidwayInvalidConfigError = exports.MidwayConfigMissingError = exports.MidwayFeatureNotImplementedError = exports.MidwayFeatureNoLongerSupportedError = exports.MidwayDefinitionNotFoundError = exports.MidwayParameterError = exports.MidwayCommonError = exports.FrameworkErrorEnum = void 0;
3
+ exports.MidwayDuplicateControllerOptionsError = exports.MidwayDuplicateClassNameError = exports.MidwayInconsistentVersionError = exports.MidwayUtilHttpClientTimeoutError = exports.MidwayMissingImportComponentError = exports.MidwaySingletonInjectRequestError = exports.MidwayUseWrongMethodError = exports.MidwayDuplicateRouteError = exports.MidwayResolverMissingError = exports.MidwayInvalidConfigError = exports.MidwayConfigMissingError = exports.MidwayFeatureNotImplementedError = exports.MidwayFeatureNoLongerSupportedError = exports.MidwayDefinitionNotFoundError = exports.MidwayParameterError = exports.MidwayCommonError = exports.FrameworkErrorEnum = void 0;
4
4
  const base_1 = require("./base");
5
5
  exports.FrameworkErrorEnum = (0, base_1.registerErrorCode)('midway', {
6
6
  UNKNOWN: 10000,
@@ -19,6 +19,7 @@ exports.FrameworkErrorEnum = (0, base_1.registerErrorCode)('midway', {
19
19
  INCONSISTENT_VERSION: 10013,
20
20
  INVALID_CONFIG: 10014,
21
21
  DUPLICATE_CLASS_NAME: 10015,
22
+ DUPLICATE_CONTROLLER_PREFIX_OPTIONS: 10016,
22
23
  });
23
24
  class MidwayCommonError extends base_1.MidwayError {
24
25
  constructor(message) {
@@ -129,4 +130,10 @@ class MidwayDuplicateClassNameError extends base_1.MidwayError {
129
130
  }
130
131
  }
131
132
  exports.MidwayDuplicateClassNameError = MidwayDuplicateClassNameError;
133
+ class MidwayDuplicateControllerOptionsError extends base_1.MidwayError {
134
+ constructor(prefix, existController, existControllerOther) {
135
+ super(`"Prefix ${prefix}" with duplicated controller options between "${existController}" and "${existControllerOther}"`, exports.FrameworkErrorEnum.DUPLICATE_CONTROLLER_PREFIX_OPTIONS);
136
+ }
137
+ }
138
+ exports.MidwayDuplicateControllerOptionsError = MidwayDuplicateControllerOptionsError;
132
139
  //# sourceMappingURL=framework.js.map
package/dist/index.d.ts CHANGED
@@ -8,8 +8,6 @@ export { safelyGet, safeRequire, delegateTargetPrototypeMethod, delegateTargetMe
8
8
  export { extend } from './util/extend';
9
9
  export * from './util/pathFileUtil';
10
10
  export * from './util/webRouterParam';
11
- export * from './common/webRouterCollector';
12
- export * from './common/triggerCollector';
13
11
  export { createConfiguration } from './functional/configuration';
14
12
  export { MidwayConfigService } from './service/configService';
15
13
  export { MidwayEnvironmentService } from './service/environmentService';
@@ -21,10 +19,12 @@ export { MidwayLifeCycleService } from './service/lifeCycleService';
21
19
  export { MidwayMiddlewareService } from './service/middlewareService';
22
20
  export { MidwayDecoratorService } from './service/decoratorService';
23
21
  export { MidwayMockService } from './service/mockService';
22
+ export { RouterInfo, DynamicRouterInfo, RouterPriority, RouterCollectorOptions, MidwayWebRouterService, } from './service/webRouterService';
23
+ export { MidwayServerlessFunctionService, WebRouterCollector, } from './service/slsFunctionService';
24
+ export { DataSourceManager } from './common/dataSourceManager';
24
25
  export * from './service/pipelineService';
25
26
  export * from './util/contextUtil';
26
27
  export * from './common/serviceFactory';
27
- export * from './common/dataSourceManager';
28
28
  export * from './common/dataListener';
29
29
  export * from './common/fileDetector';
30
30
  export * from './common/webGenerator';
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.MidwayFrameworkType = exports.MidwayMockService = exports.MidwayDecoratorService = exports.MidwayMiddlewareService = exports.MidwayLifeCycleService = exports.MidwayAspectService = exports.MidwayFrameworkService = exports.MidwayLoggerService = exports.MidwayInformationService = exports.MidwayEnvironmentService = exports.MidwayConfigService = exports.createConfiguration = exports.extend = exports.wrapAsync = exports.wrapMiddleware = exports.pathMatching = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetPrototypeMethod = exports.safeRequire = exports.safelyGet = exports.BaseFramework = exports.MidwayRequestContainer = void 0;
17
+ exports.MidwayFrameworkType = exports.DataSourceManager = exports.WebRouterCollector = exports.MidwayServerlessFunctionService = exports.MidwayWebRouterService = exports.MidwayMockService = exports.MidwayDecoratorService = exports.MidwayMiddlewareService = exports.MidwayLifeCycleService = exports.MidwayAspectService = exports.MidwayFrameworkService = exports.MidwayLoggerService = exports.MidwayInformationService = exports.MidwayEnvironmentService = exports.MidwayConfigService = exports.createConfiguration = exports.extend = exports.wrapAsync = exports.wrapMiddleware = exports.pathMatching = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetPrototypeMethod = exports.safeRequire = exports.safelyGet = exports.BaseFramework = exports.MidwayRequestContainer = void 0;
18
18
  __exportStar(require("./interface"), exports);
19
19
  __exportStar(require("./context/container"), exports);
20
20
  var requestContainer_1 = require("./context/requestContainer");
@@ -39,8 +39,6 @@ var extend_1 = require("./util/extend");
39
39
  Object.defineProperty(exports, "extend", { enumerable: true, get: function () { return extend_1.extend; } });
40
40
  __exportStar(require("./util/pathFileUtil"), exports);
41
41
  __exportStar(require("./util/webRouterParam"), exports);
42
- __exportStar(require("./common/webRouterCollector"), exports);
43
- __exportStar(require("./common/triggerCollector"), exports);
44
42
  var configuration_1 = require("./functional/configuration");
45
43
  Object.defineProperty(exports, "createConfiguration", { enumerable: true, get: function () { return configuration_1.createConfiguration; } });
46
44
  var configService_1 = require("./service/configService");
@@ -63,10 +61,16 @@ var decoratorService_1 = require("./service/decoratorService");
63
61
  Object.defineProperty(exports, "MidwayDecoratorService", { enumerable: true, get: function () { return decoratorService_1.MidwayDecoratorService; } });
64
62
  var mockService_1 = require("./service/mockService");
65
63
  Object.defineProperty(exports, "MidwayMockService", { enumerable: true, get: function () { return mockService_1.MidwayMockService; } });
64
+ var webRouterService_1 = require("./service/webRouterService");
65
+ Object.defineProperty(exports, "MidwayWebRouterService", { enumerable: true, get: function () { return webRouterService_1.MidwayWebRouterService; } });
66
+ var slsFunctionService_1 = require("./service/slsFunctionService");
67
+ Object.defineProperty(exports, "MidwayServerlessFunctionService", { enumerable: true, get: function () { return slsFunctionService_1.MidwayServerlessFunctionService; } });
68
+ Object.defineProperty(exports, "WebRouterCollector", { enumerable: true, get: function () { return slsFunctionService_1.WebRouterCollector; } });
69
+ var dataSourceManager_1 = require("./common/dataSourceManager");
70
+ Object.defineProperty(exports, "DataSourceManager", { enumerable: true, get: function () { return dataSourceManager_1.DataSourceManager; } });
66
71
  __exportStar(require("./service/pipelineService"), exports);
67
72
  __exportStar(require("./util/contextUtil"), exports);
68
73
  __exportStar(require("./common/serviceFactory"), exports);
69
- __exportStar(require("./common/dataSourceManager"), exports);
70
74
  __exportStar(require("./common/dataListener"), exports);
71
75
  __exportStar(require("./common/fileDetector"), exports);
72
76
  __exportStar(require("./common/webGenerator"), exports);
@@ -314,10 +314,7 @@ export declare type FunctionMiddleware<CTX, R, N = unknown> = N extends true ? (
314
314
  export declare type ClassMiddleware<CTX, R, N> = new (...args: any[]) => IMiddleware<CTX, R, N>;
315
315
  export declare type CommonMiddleware<CTX, R, N> = ClassMiddleware<CTX, R, N> | FunctionMiddleware<CTX, R, N>;
316
316
  export declare type CommonMiddlewareUnion<CTX, R, N> = CommonMiddleware<CTX, R, N> | Array<CommonMiddleware<CTX, R, N>>;
317
- export declare type MiddlewareRespond<CTX, R, N> = (context: CTX, nextOrRes?: N extends true ? R : NextFunction, next?: N) => Promise<{
318
- result: any;
319
- error: Error | undefined;
320
- }>;
317
+ export declare type MiddlewareRespond<CTX, R, N> = (context: CTX, nextOrRes?: N extends true ? R : NextFunction, next?: N) => Promise<any>;
321
318
  /**
322
319
  * Common Exception Filter definition
323
320
  */
@@ -175,11 +175,17 @@ let MidwayConfigService = class MidwayConfigService {
175
175
  let exports = typeof configFilename === 'string'
176
176
  ? require(configFilename)
177
177
  : configFilename;
178
- if (exports && exports.default) {
179
- if (Object.keys(exports).length > 1) {
180
- throw new error_1.MidwayInvalidConfigError(`${configFilename} should not have both a default export and named export`);
178
+ // if es module
179
+ if (exports && exports.__esModule) {
180
+ if (exports && exports.default) {
181
+ if (Object.keys(exports).length > 1) {
182
+ throw new error_1.MidwayInvalidConfigError(`${configFilename} should not have both a default export and named export`);
183
+ }
184
+ exports = exports.default;
181
185
  }
182
- exports = exports.default;
186
+ }
187
+ else {
188
+ console.log(exports);
183
189
  }
184
190
  return exports;
185
191
  }
@@ -50,11 +50,11 @@ let MidwayFrameworkService = class MidwayFrameworkService {
50
50
  return new pipelineService_1.MidwayPipelineService((_b = (_a = instance[interface_1.REQUEST_OBJ_CTX_KEY]) === null || _a === void 0 ? void 0 : _a.requestContext) !== null && _b !== void 0 ? _b : this.applicationContext, meta.valves);
51
51
  });
52
52
  // register @App decorator handler
53
- this.decoratorService.registerPropertyHandler(decorator_1.APPLICATION_KEY, (propertyName, mete) => {
54
- if (mete.type) {
55
- const framework = this.applicationManager.getApplication(mete.type);
53
+ this.decoratorService.registerPropertyHandler(decorator_1.APPLICATION_KEY, (propertyName, meta) => {
54
+ if (meta.type) {
55
+ const framework = this.applicationManager.getApplication(meta.type);
56
56
  if (!framework) {
57
- throw new error_1.MidwayCommonError(`Framework ${mete.type} not Found`);
57
+ throw new error_1.MidwayCommonError(`Framework ${meta.type} not Found`);
58
58
  }
59
59
  return framework;
60
60
  }
@@ -62,8 +62,9 @@ let MidwayFrameworkService = class MidwayFrameworkService {
62
62
  return this.getMainApp();
63
63
  }
64
64
  });
65
- this.decoratorService.registerPropertyHandler(decorator_1.PLUGIN_KEY, (key, target) => {
66
- return this.getMainApp()[key];
65
+ this.decoratorService.registerPropertyHandler(decorator_1.PLUGIN_KEY, (propertyName, meta) => {
66
+ var _a;
67
+ return this.getMainApp()[(_a = meta.identifier) !== null && _a !== void 0 ? _a : propertyName];
67
68
  });
68
69
  let frameworks = (0, decorator_1.listModule)(decorator_1.FRAMEWORK_KEY);
69
70
  // filter proto
@@ -88,13 +88,17 @@ let MidwayMiddlewareService = class MidwayMiddlewareService {
88
88
  return Promise.resolve(fn(context, dispatch.bind(null, i + 1), {
89
89
  index,
90
90
  })).then(result => {
91
- // need to set body
92
- if (context['body'] && !result) {
93
- result = context['body'];
94
- }
95
- else if (result && context['body'] !== result) {
91
+ /**
92
+ * 1、return ctx.body,return 的优先级更高
93
+ * 2、如果 result 有值(非 undefined),则不管什么情况,都会覆盖当前 body,注意,这里有可能赋值 null,导致 status 为 204,会在中间件处进行修正
94
+ * 3、如果 result 没值,且 ctx.body 已经赋值,则向 result 赋值
95
+ */
96
+ if (result !== undefined) {
96
97
  context['body'] = result;
97
98
  }
99
+ else if (context['body'] !== undefined) {
100
+ result = context['body'];
101
+ }
98
102
  return result;
99
103
  });
100
104
  }
@@ -0,0 +1,25 @@
1
+ import { FaaSMetadata } from '@midwayjs/decorator';
2
+ import { MidwayWebRouterService, RouterCollectorOptions, RouterInfo, RouterPriority } from './webRouterService';
3
+ export declare class MidwayServerlessFunctionService extends MidwayWebRouterService {
4
+ readonly options: RouterCollectorOptions;
5
+ constructor(options?: RouterCollectorOptions);
6
+ protected analyze(): Promise<void>;
7
+ protected analyzeFunction(): void;
8
+ protected collectFunctionRoute(module: any): void;
9
+ getFunctionList(): Promise<RouterInfo[]>;
10
+ addServerlessFunction(func: (...args: any[]) => Promise<any>, triggerOptions: FaaSMetadata.TriggerMetadata, functionOptions?: FaaSMetadata.ServerlessFunctionOptions): void;
11
+ }
12
+ /**
13
+ * @deprecated use built-in MidwayWebRouterService first
14
+ */
15
+ export declare class WebRouterCollector {
16
+ private baseDir;
17
+ private options;
18
+ private proxy;
19
+ constructor(baseDir?: string, options?: RouterCollectorOptions);
20
+ protected init(): Promise<void>;
21
+ getRoutePriorityList(): Promise<RouterPriority[]>;
22
+ getRouterTable(): Promise<Map<string, RouterInfo[]>>;
23
+ getFlattenRouterTable(): Promise<RouterInfo[]>;
24
+ }
25
+ //# sourceMappingURL=slsFunctionService.d.ts.map
@@ -0,0 +1,240 @@
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
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.WebRouterCollector = exports.MidwayServerlessFunctionService = void 0;
13
+ const decorator_1 = require("@midwayjs/decorator");
14
+ const webRouterService_1 = require("./webRouterService");
15
+ const container_1 = require("../context/container");
16
+ const fileDetector_1 = require("../common/fileDetector");
17
+ const contextUtil_1 = require("../util/contextUtil");
18
+ let MidwayServerlessFunctionService = class MidwayServerlessFunctionService extends webRouterService_1.MidwayWebRouterService {
19
+ constructor(options = {}) {
20
+ super(Object.assign({}, options, {
21
+ includeFunctionRouter: true,
22
+ }));
23
+ this.options = options;
24
+ }
25
+ async analyze() {
26
+ this.analyzeController();
27
+ this.analyzeFunction();
28
+ this.sortPrefixAndRouter();
29
+ // requestMethod all transform to other method
30
+ for (const routerInfo of this.routes.values()) {
31
+ for (const info of routerInfo) {
32
+ if (info.requestMethod === 'all') {
33
+ info.functionTriggerMetadata.method = [
34
+ 'get',
35
+ 'post',
36
+ 'put',
37
+ 'delete',
38
+ 'head',
39
+ 'patch',
40
+ 'options',
41
+ ];
42
+ }
43
+ }
44
+ }
45
+ }
46
+ analyzeFunction() {
47
+ const fnModules = (0, decorator_1.listModule)(decorator_1.FUNC_KEY);
48
+ for (const module of fnModules) {
49
+ this.collectFunctionRoute(module);
50
+ }
51
+ }
52
+ collectFunctionRoute(module) {
53
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
54
+ // serverlessTrigger metadata
55
+ const webRouterInfo = (0, decorator_1.getClassMetadata)(decorator_1.FUNC_KEY, module);
56
+ const controllerId = (0, decorator_1.getProviderName)(module);
57
+ const id = (0, decorator_1.getProviderUUId)(module);
58
+ const prefix = '/';
59
+ if (!this.routes.has(prefix)) {
60
+ this.routes.set(prefix, []);
61
+ this.routesPriority.push({
62
+ prefix,
63
+ priority: -999,
64
+ middleware: [],
65
+ routerOptions: {},
66
+ controllerId,
67
+ routerModule: module,
68
+ });
69
+ }
70
+ for (const webRouter of webRouterInfo) {
71
+ // 新的 @ServerlessTrigger 写法
72
+ if ((_a = webRouter['metadata']) === null || _a === void 0 ? void 0 : _a['path']) {
73
+ const routeArgsInfo = (0, decorator_1.getPropertyDataFromClass)(decorator_1.WEB_ROUTER_PARAM_KEY, module, webRouter['methodName']) || [];
74
+ const routerResponseData = (0, decorator_1.getPropertyMetadata)(decorator_1.WEB_RESPONSE_KEY, module, webRouter['methodName']) || [];
75
+ // 新 http/api gateway 函数
76
+ const data = {
77
+ id,
78
+ prefix,
79
+ routerName: '',
80
+ url: webRouter['metadata']['path'],
81
+ requestMethod: (_c = (_b = webRouter['metadata']) === null || _b === void 0 ? void 0 : _b['method']) !== null && _c !== void 0 ? _c : 'get',
82
+ method: webRouter['methodName'],
83
+ description: '',
84
+ summary: '',
85
+ handlerName: `${controllerId}.${webRouter['methodName']}`,
86
+ funcHandlerName: `${controllerId}.${webRouter['methodName']}`,
87
+ controllerId,
88
+ middleware: ((_d = webRouter['metadata']) === null || _d === void 0 ? void 0 : _d['middleware']) || [],
89
+ controllerMiddleware: [],
90
+ requestMetadata: routeArgsInfo,
91
+ responseMetadata: routerResponseData,
92
+ };
93
+ const functionMeta = (0, decorator_1.getPropertyMetadata)(decorator_1.SERVERLESS_FUNC_KEY, module, webRouter['methodName']) || {};
94
+ const functionName = (_f = (_e = functionMeta['functionName']) !== null && _e !== void 0 ? _e : webRouter['functionName']) !== null && _f !== void 0 ? _f : createFunctionName(module, webRouter['methodName']);
95
+ data.functionName = functionName;
96
+ data.functionTriggerName = webRouter['type'];
97
+ data.functionTriggerMetadata = webRouter['metadata'];
98
+ data.functionMetadata = {
99
+ functionName,
100
+ ...functionMeta,
101
+ };
102
+ this.checkDuplicateAndPush(prefix, data);
103
+ }
104
+ else {
105
+ const functionMeta = (0, decorator_1.getPropertyMetadata)(decorator_1.SERVERLESS_FUNC_KEY, module, webRouter['methodName']) || {};
106
+ const functionName = (_h = (_g = functionMeta['functionName']) !== null && _g !== void 0 ? _g : webRouter['functionName']) !== null && _h !== void 0 ? _h : createFunctionName(module, webRouter['methodName']);
107
+ // 其他类型的函数
108
+ this.checkDuplicateAndPush(prefix, {
109
+ id,
110
+ prefix,
111
+ routerName: '',
112
+ url: '',
113
+ requestMethod: '',
114
+ method: webRouter['methodName'],
115
+ description: '',
116
+ summary: '',
117
+ handlerName: `${controllerId}.${webRouter['methodName']}`,
118
+ funcHandlerName: `${controllerId}.${webRouter['methodName']}`,
119
+ controllerId,
120
+ middleware: ((_j = webRouter['metadata']) === null || _j === void 0 ? void 0 : _j['middleware']) || [],
121
+ controllerMiddleware: [],
122
+ requestMetadata: [],
123
+ responseMetadata: [],
124
+ functionName,
125
+ functionTriggerName: webRouter['type'],
126
+ functionTriggerMetadata: webRouter['metadata'],
127
+ functionMetadata: {
128
+ functionName,
129
+ ...functionMeta,
130
+ },
131
+ });
132
+ }
133
+ }
134
+ }
135
+ async getFunctionList() {
136
+ return this.getFlattenRouterTable();
137
+ }
138
+ addServerlessFunction(func, triggerOptions, functionOptions = {}) {
139
+ var _a, _b;
140
+ const prefix = '/';
141
+ if (!this.routes.has(prefix)) {
142
+ this.routes.set(prefix, []);
143
+ this.routesPriority.push({
144
+ prefix,
145
+ priority: -999,
146
+ middleware: [],
147
+ routerOptions: {},
148
+ controllerId: undefined,
149
+ routerModule: module,
150
+ });
151
+ }
152
+ const functionName = (_a = triggerOptions.functionName) !== null && _a !== void 0 ? _a : functionOptions.functionName;
153
+ this.checkDuplicateAndPush(prefix, {
154
+ id: null,
155
+ method: func,
156
+ url: triggerOptions.metadata['path'] || '',
157
+ requestMethod: triggerOptions.metadata['method'] || '',
158
+ description: '',
159
+ summary: '',
160
+ handlerName: '',
161
+ funcHandlerName: triggerOptions.handlerName || functionOptions.handlerName,
162
+ controllerId: '',
163
+ middleware: ((_b = triggerOptions.metadata) === null || _b === void 0 ? void 0 : _b.middleware) || [],
164
+ controllerMiddleware: [],
165
+ requestMetadata: [],
166
+ responseMetadata: [],
167
+ functionName,
168
+ functionTriggerName: triggerOptions.metadata.name,
169
+ functionTriggerMetadata: triggerOptions.metadata,
170
+ functionMetadata: {
171
+ functionName,
172
+ ...functionOptions,
173
+ },
174
+ });
175
+ }
176
+ };
177
+ MidwayServerlessFunctionService = __decorate([
178
+ (0, decorator_1.Provide)(),
179
+ (0, decorator_1.Scope)(decorator_1.ScopeEnum.Singleton),
180
+ __metadata("design:paramtypes", [Object])
181
+ ], MidwayServerlessFunctionService);
182
+ exports.MidwayServerlessFunctionService = MidwayServerlessFunctionService;
183
+ function createFunctionName(target, functionName) {
184
+ return (0, decorator_1.getProviderName)(target).replace(/[:#]/g, '-') + '-' + functionName;
185
+ }
186
+ /**
187
+ * @deprecated use built-in MidwayWebRouterService first
188
+ */
189
+ class WebRouterCollector {
190
+ constructor(baseDir = '', options = {}) {
191
+ this.baseDir = baseDir;
192
+ this.options = options;
193
+ }
194
+ async init() {
195
+ if (!this.proxy) {
196
+ if (this.baseDir) {
197
+ const container = new container_1.MidwayContainer();
198
+ (0, decorator_1.bindContainer)(container);
199
+ container.setFileDetector(new fileDetector_1.DirectoryFileDetector({
200
+ loadDir: this.baseDir,
201
+ }));
202
+ await container.ready();
203
+ }
204
+ if (this.options.includeFunctionRouter) {
205
+ if ((0, contextUtil_1.getCurrentMainFramework)()) {
206
+ this.proxy = await (0, contextUtil_1.getCurrentMainFramework)()
207
+ .getApplicationContext()
208
+ .getAsync(MidwayServerlessFunctionService, [this.options]);
209
+ }
210
+ else {
211
+ this.proxy = new MidwayServerlessFunctionService(this.options);
212
+ }
213
+ }
214
+ else {
215
+ if ((0, contextUtil_1.getCurrentMainFramework)()) {
216
+ this.proxy = await (0, contextUtil_1.getCurrentMainFramework)()
217
+ .getApplicationContext()
218
+ .getAsync(webRouterService_1.MidwayWebRouterService, [this.options]);
219
+ }
220
+ else {
221
+ this.proxy = new webRouterService_1.MidwayWebRouterService(this.options);
222
+ }
223
+ }
224
+ }
225
+ }
226
+ async getRoutePriorityList() {
227
+ await this.init();
228
+ return this.proxy.getRoutePriorityList();
229
+ }
230
+ async getRouterTable() {
231
+ await this.init();
232
+ return this.proxy.getRouterTable();
233
+ }
234
+ async getFlattenRouterTable() {
235
+ await this.init();
236
+ return this.proxy.getFlattenRouterTable();
237
+ }
238
+ }
239
+ exports.WebRouterCollector = WebRouterCollector;
240
+ //# sourceMappingURL=slsFunctionService.js.map
@@ -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,40 @@ 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
+ summary?: string;
31
32
  /**
32
33
  * router handler function key,for IoC container load
33
34
  */
34
- handlerName: string;
35
+ handlerName?: string;
35
36
  /**
36
37
  * serverless func load key
37
38
  */
38
- funcHandlerName: string;
39
+ funcHandlerName?: string;
39
40
  /**
40
41
  * controller provideId
41
42
  */
42
- controllerId: string;
43
+ controllerId?: string;
43
44
  /**
44
45
  * router middleware
45
46
  */
46
- middleware: any[];
47
+ middleware?: any[];
47
48
  /**
48
49
  * controller middleware in this router
49
50
  */
50
- controllerMiddleware: any[];
51
+ controllerMiddleware?: any[];
51
52
  /**
52
53
  * request args metadata
53
54
  */
54
- requestMetadata: any[];
55
+ requestMetadata?: any[];
55
56
  /**
56
57
  * response data metadata
57
58
  */
58
- responseMetadata: any[];
59
+ responseMetadata?: any[];
59
60
  /**
60
61
  * serverless function name
61
62
  */
@@ -73,6 +74,7 @@ export interface RouterInfo {
73
74
  */
74
75
  functionMetadata?: any;
75
76
  }
77
+ export declare type DynamicRouterInfo = Omit<RouterInfo, 'id' | 'url' | 'prefix' | 'method' | 'controllerId' | 'controllerMiddleware' | 'responseMetadata'>;
76
78
  export interface RouterPriority {
77
79
  prefix: string;
78
80
  priority: number;
@@ -88,16 +90,29 @@ export interface RouterCollectorOptions {
88
90
  includeFunctionRouter?: boolean;
89
91
  globalPrefix?: string;
90
92
  }
91
- export declare class WebRouterCollector {
92
- protected readonly baseDir: string;
93
+ export declare class MidwayWebRouterService {
94
+ readonly options: RouterCollectorOptions;
93
95
  private isReady;
94
96
  protected routes: Map<string, RouterInfo[]>;
95
- private routesPriority;
96
- protected options: RouterCollectorOptions;
97
- constructor(baseDir?: string, options?: RouterCollectorOptions);
97
+ protected routesPriority: RouterPriority[];
98
+ constructor(options?: RouterCollectorOptions);
98
99
  protected analyze(): Promise<void>;
99
- protected collectRoute(module: any, functionMeta?: boolean): void;
100
- protected collectFunctionRoute(module: any, functionMeta?: boolean): void;
100
+ protected analyzeController(): void;
101
+ protected sortPrefixAndRouter(): void;
102
+ /**
103
+ * dynamically add a controller
104
+ * @param controllerClz
105
+ * @param controllerOption
106
+ * @param functionMeta
107
+ */
108
+ addController(controllerClz: any, controllerOption: ControllerOption, functionMeta?: boolean): void;
109
+ /**
110
+ * dynamically add a route to root prefix
111
+ * @param routerPath
112
+ * @param routerFunction
113
+ * @param routerInfoOption
114
+ */
115
+ addRouter(routerPath: string | RegExp, routerFunction: (...args: any[]) => void, routerInfoOption: DynamicRouterInfo): void;
101
116
  sortRouter(urlMatchList: RouterInfo[]): {
102
117
  _pureRouter: string;
103
118
  _level: number;
@@ -107,15 +122,15 @@ export declare class WebRouterCollector {
107
122
  /**
108
123
  * uuid
109
124
  */
110
- id: string;
125
+ id?: string;
111
126
  /**
112
127
  * router prefix from controller
113
128
  */
114
- prefix: string;
129
+ prefix?: string;
115
130
  /**
116
131
  * router alias name
117
132
  */
118
- routerName: string;
133
+ routerName?: string;
119
134
  /**
120
135
  * router path, without prefix
121
136
  */
@@ -127,40 +142,40 @@ export declare class WebRouterCollector {
127
142
  /**
128
143
  * invoke function method
129
144
  */
130
- method: string;
145
+ method: string | ((...args: any[]) => void);
131
146
  /**
132
147
  * router description
133
148
  */
134
- description: string;
135
- summary: string;
149
+ description?: string;
150
+ summary?: string;
136
151
  /**
137
152
  * router handler function key,for IoC container load
138
153
  */
139
- handlerName: string;
154
+ handlerName?: string;
140
155
  /**
141
156
  * serverless func load key
142
157
  */
143
- funcHandlerName: string;
158
+ funcHandlerName?: string;
144
159
  /**
145
160
  * controller provideId
146
161
  */
147
- controllerId: string;
162
+ controllerId?: string;
148
163
  /**
149
164
  * router middleware
150
165
  */
151
- middleware: any[];
166
+ middleware?: any[];
152
167
  /**
153
168
  * controller middleware in this router
154
169
  */
155
- controllerMiddleware: any[];
170
+ controllerMiddleware?: any[];
156
171
  /**
157
172
  * request args metadata
158
173
  */
159
- requestMetadata: any[];
174
+ requestMetadata?: any[];
160
175
  /**
161
176
  * response data metadata
162
177
  */
163
- responseMetadata: any[];
178
+ responseMetadata?: any[];
164
179
  /**
165
180
  * serverless function name
166
181
  */
@@ -181,6 +196,6 @@ export declare class WebRouterCollector {
181
196
  getRoutePriorityList(): Promise<RouterPriority[]>;
182
197
  getRouterTable(): Promise<Map<string, RouterInfo[]>>;
183
198
  getFlattenRouterTable(): Promise<RouterInfo[]>;
184
- private checkDuplicateAndPush;
199
+ protected checkDuplicateAndPush(prefix: any, routerInfo: RouterInfo): void;
185
200
  }
186
- //# sourceMappingURL=webRouterCollector.d.ts.map
201
+ //# sourceMappingURL=webRouterService.d.ts.map
@@ -1,39 +1,39 @@
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");
10
17
  const debug = util.debuglog('midway:debug');
11
- class WebRouterCollector {
12
- constructor(baseDir = '', options = {}) {
18
+ let MidwayWebRouterService = class MidwayWebRouterService {
19
+ constructor(options = {}) {
20
+ this.options = options;
13
21
  this.isReady = false;
14
22
  this.routes = new Map();
15
23
  this.routesPriority = [];
16
- this.baseDir = baseDir;
17
- this.options = options;
18
24
  }
19
25
  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
- }
26
+ this.analyzeController();
27
+ this.sortPrefixAndRouter();
28
+ }
29
+ analyzeController() {
27
30
  const controllerModules = (0, decorator_1.listModule)(decorator_1.CONTROLLER_KEY);
28
31
  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
- }
32
+ const controllerOption = (0, decorator_1.getClassMetadata)(decorator_1.CONTROLLER_KEY, module);
33
+ this.addController(module, controllerOption, this.options.includeFunctionRouter);
36
34
  }
35
+ }
36
+ sortPrefixAndRouter() {
37
37
  // filter empty prefix
38
38
  this.routesPriority = this.routesPriority.filter(item => {
39
39
  const prefixList = this.routes.get(item.prefix);
@@ -55,12 +55,17 @@ class WebRouterCollector {
55
55
  return routeB.prefix.length - routeA.prefix.length;
56
56
  });
57
57
  }
58
- collectRoute(module, functionMeta = false) {
58
+ /**
59
+ * dynamically add a controller
60
+ * @param controllerClz
61
+ * @param controllerOption
62
+ * @param functionMeta
63
+ */
64
+ addController(controllerClz, controllerOption, functionMeta = false) {
59
65
  var _a;
60
- const controllerId = (0, decorator_1.getProviderName)(module);
66
+ const controllerId = (0, decorator_1.getProviderName)(controllerClz);
61
67
  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);
68
+ const id = (0, decorator_1.getProviderUUId)(controllerClz);
64
69
  let priority;
65
70
  // implement middleware in controller
66
71
  const middleware = controllerOption.routerOptions.middleware;
@@ -83,9 +88,18 @@ class WebRouterCollector {
83
88
  middleware,
84
89
  routerOptions: controllerOption.routerOptions,
85
90
  controllerId,
86
- routerModule: module,
91
+ routerModule: controllerClz,
87
92
  });
88
93
  }
94
+ else {
95
+ // 不同的 controller,可能会有相同的 prefix,一旦 options 不同,就要报错
96
+ if (middleware) {
97
+ const originRoute = this.routesPriority.filter(el => {
98
+ return el.prefix === prefix;
99
+ })[0];
100
+ throw new error_1.MidwayDuplicateControllerOptionsError(prefix, controllerId, originRoute.controllerId);
101
+ }
102
+ }
89
103
  // set ignorePrefix
90
104
  if (!this.routes.has(ignorePrefix)) {
91
105
  this.routes.set(ignorePrefix, []);
@@ -95,14 +109,14 @@ class WebRouterCollector {
95
109
  middleware,
96
110
  routerOptions: controllerOption.routerOptions,
97
111
  controllerId,
98
- routerModule: module,
112
+ routerModule: controllerClz,
99
113
  });
100
114
  }
101
- const webRouterInfo = (0, decorator_1.getClassMetadata)(decorator_1.WEB_ROUTER_KEY, module);
115
+ const webRouterInfo = (0, decorator_1.getClassMetadata)(decorator_1.WEB_ROUTER_KEY, controllerClz);
102
116
  if (webRouterInfo && typeof webRouterInfo[Symbol.iterator] === 'function') {
103
117
  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) || [];
118
+ const routeArgsInfo = (0, decorator_1.getPropertyDataFromClass)(decorator_1.WEB_ROUTER_PARAM_KEY, controllerClz, webRouter.method) || [];
119
+ const routerResponseData = (0, decorator_1.getPropertyMetadata)(decorator_1.WEB_RESPONSE_KEY, controllerClz, webRouter.method) || [];
106
120
  const data = {
107
121
  id,
108
122
  prefix: webRouter.ignoreGlobalPrefix ? ignorePrefix : prefix,
@@ -136,92 +150,17 @@ class WebRouterCollector {
136
150
  }
137
151
  }
138
152
  }
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 = '/';
146
- if (!this.routes.has(prefix)) {
147
- this.routes.set(prefix, []);
148
- this.routesPriority.push({
149
- prefix,
150
- priority: -999,
151
- middleware: [],
152
- routerOptions: {},
153
- controllerId,
154
- routerModule: module,
155
- });
156
- }
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
- }
153
+ /**
154
+ * dynamically add a route to root prefix
155
+ * @param routerPath
156
+ * @param routerFunction
157
+ * @param routerInfoOption
158
+ */
159
+ addRouter(routerPath, routerFunction, routerInfoOption) {
160
+ this.checkDuplicateAndPush('/', Object.assign(routerInfoOption, {
161
+ method: routerFunction,
162
+ url: routerPath,
163
+ }));
225
164
  }
226
165
  sortRouter(urlMatchList) {
227
166
  // 1. 绝对路径规则优先级最高如 /ab/cb/e
@@ -323,9 +262,11 @@ class WebRouterCollector {
323
262
  }
324
263
  prefixList.push(routerInfo);
325
264
  }
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
265
+ };
266
+ MidwayWebRouterService = __decorate([
267
+ (0, decorator_1.Provide)(),
268
+ (0, decorator_1.Scope)(decorator_1.ScopeEnum.Singleton),
269
+ __metadata("design:paramtypes", [Object])
270
+ ], MidwayWebRouterService);
271
+ exports.MidwayWebRouterService = MidwayWebRouterService;
272
+ //# 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) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/core",
3
- "version": "3.4.0-beta.1",
3
+ "version": "3.4.0-beta.4",
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.4.0-beta.1",
24
+ "@midwayjs/decorator": "^3.4.0-beta.4",
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": "14d8440f20978426184c988808343cc24bcf6e20"
48
+ "gitHead": "3b686101f7802f87d47b8c9d25561339d556e573"
49
49
  }
@@ -1,8 +0,0 @@
1
- import { RouterInfo, WebRouterCollector } from './webRouterCollector';
2
- export declare class ServerlessTriggerCollector extends WebRouterCollector {
3
- protected analyze(): Promise<void>;
4
- protected collectRoute(module: any): void;
5
- protected collectFunctionRoute(module: any): void;
6
- getFunctionList(): Promise<RouterInfo[]>;
7
- }
8
- //# sourceMappingURL=triggerCollector.d.ts.map
@@ -1,37 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ServerlessTriggerCollector = void 0;
4
- const webRouterCollector_1 = require("./webRouterCollector");
5
- class ServerlessTriggerCollector extends webRouterCollector_1.WebRouterCollector {
6
- async analyze() {
7
- this.options.includeFunctionRouter = true;
8
- await super.analyze();
9
- // requestMethod all transform to other method
10
- for (const routerInfo of this.routes.values()) {
11
- for (const info of routerInfo) {
12
- if (info.requestMethod === 'all') {
13
- info.functionTriggerMetadata.method = [
14
- 'get',
15
- 'post',
16
- 'put',
17
- 'delete',
18
- 'head',
19
- 'patch',
20
- 'options',
21
- ];
22
- }
23
- }
24
- }
25
- }
26
- collectRoute(module) {
27
- super.collectRoute(module, true);
28
- }
29
- collectFunctionRoute(module) {
30
- super.collectFunctionRoute(module, true);
31
- }
32
- async getFunctionList() {
33
- return this.getFlattenRouterTable();
34
- }
35
- }
36
- exports.ServerlessTriggerCollector = ServerlessTriggerCollector;
37
- //# sourceMappingURL=triggerCollector.js.map