@midwayjs/core 3.4.0-beta.2 → 3.4.0-beta.5

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
@@ -115,7 +115,7 @@ class WebControllerGenerator {
115
115
  debug(`[core]: Load Router "${routeInfo.requestMethod.toUpperCase()} ${routeInfo.url}"`);
116
116
  // apply controller from request context
117
117
  // eslint-disable-next-line prefer-spread
118
- newRouter[routeInfo.requestMethod].apply(newRouter, routerArgs);
118
+ newRouter[routeInfo.requestMethod.toLowerCase()].apply(newRouter, routerArgs);
119
119
  }
120
120
  routerHandler && routerHandler(newRouter);
121
121
  }
@@ -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
@@ -19,11 +19,12 @@ export { MidwayLifeCycleService } from './service/lifeCycleService';
19
19
  export { MidwayMiddlewareService } from './service/middlewareService';
20
20
  export { MidwayDecoratorService } from './service/decoratorService';
21
21
  export { MidwayMockService } from './service/mockService';
22
- export { RouterInfo, DynamicRouterInfo, RouterPriority, RouterCollectorOptions, MidwayWebRouterService, WebRouterCollector, } from './service/webRouterService';
22
+ export { RouterInfo, DynamicRouterInfo, RouterPriority, RouterCollectorOptions, MidwayWebRouterService, } from './service/webRouterService';
23
+ export { MidwayServerlessFunctionService, WebRouterCollector, } from './service/slsFunctionService';
24
+ export { DataSourceManager } from './common/dataSourceManager';
23
25
  export * from './service/pipelineService';
24
26
  export * from './util/contextUtil';
25
27
  export * from './common/serviceFactory';
26
- export * from './common/dataSourceManager';
27
28
  export * from './common/dataListener';
28
29
  export * from './common/fileDetector';
29
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.WebRouterCollector = 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;
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");
@@ -63,11 +63,14 @@ var mockService_1 = require("./service/mockService");
63
63
  Object.defineProperty(exports, "MidwayMockService", { enumerable: true, get: function () { return mockService_1.MidwayMockService; } });
64
64
  var webRouterService_1 = require("./service/webRouterService");
65
65
  Object.defineProperty(exports, "MidwayWebRouterService", { enumerable: true, get: function () { return webRouterService_1.MidwayWebRouterService; } });
66
- Object.defineProperty(exports, "WebRouterCollector", { enumerable: true, get: function () { return webRouterService_1.WebRouterCollector; } });
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; } });
67
71
  __exportStar(require("./service/pipelineService"), exports);
68
72
  __exportStar(require("./util/contextUtil"), exports);
69
73
  __exportStar(require("./common/serviceFactory"), exports);
70
- __exportStar(require("./common/dataSourceManager"), exports);
71
74
  __exportStar(require("./common/dataListener"), exports);
72
75
  __exportStar(require("./common/fileDetector"), exports);
73
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,14 @@ 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;
183
186
  }
184
187
  return exports;
185
188
  }
@@ -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: undefined,
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
@@ -74,7 +74,7 @@ export interface RouterInfo {
74
74
  */
75
75
  functionMetadata?: any;
76
76
  }
77
- export declare type DynamicRouterInfo = Omit<RouterInfo, 'id' | 'url' | 'prefix' | 'method' | 'controllerId' | 'controllerMiddleware' | 'responseMetadata'>;
77
+ export declare type DynamicRouterInfo = Omit<RouterInfo, 'id' | 'method' | 'controllerId' | 'controllerMiddleware' | 'responseMetadata'>;
78
78
  export interface RouterPriority {
79
79
  prefix: string;
80
80
  priority: number;
@@ -94,9 +94,11 @@ export declare class MidwayWebRouterService {
94
94
  readonly options: RouterCollectorOptions;
95
95
  private isReady;
96
96
  protected routes: Map<string, RouterInfo[]>;
97
- private routesPriority;
97
+ protected routesPriority: RouterPriority[];
98
98
  constructor(options?: RouterCollectorOptions);
99
- private analyze;
99
+ protected analyze(): Promise<void>;
100
+ protected analyzeController(): void;
101
+ protected sortPrefixAndRouter(): void;
100
102
  /**
101
103
  * dynamically add a controller
102
104
  * @param controllerClz
@@ -110,8 +112,7 @@ export declare class MidwayWebRouterService {
110
112
  * @param routerFunction
111
113
  * @param routerInfoOption
112
114
  */
113
- addRouter(routerPath: string | RegExp, routerFunction: (...args: any[]) => void, routerInfoOption: DynamicRouterInfo): void;
114
- protected collectFunctionRoute(module: any, functionMeta?: boolean): void;
115
+ addRouter(routerFunction: (...args: any[]) => void, routerInfoOption: DynamicRouterInfo): void;
115
116
  sortRouter(urlMatchList: RouterInfo[]): {
116
117
  _pureRouter: string;
117
118
  _level: number;
@@ -195,19 +196,6 @@ export declare class MidwayWebRouterService {
195
196
  getRoutePriorityList(): Promise<RouterPriority[]>;
196
197
  getRouterTable(): Promise<Map<string, RouterInfo[]>>;
197
198
  getFlattenRouterTable(): Promise<RouterInfo[]>;
198
- private checkDuplicateAndPush;
199
- }
200
- /**
201
- * @deprecated use built-in MidwayWebRouterService first
202
- */
203
- export declare class WebRouterCollector {
204
- private baseDir;
205
- private options;
206
- private proxy;
207
- constructor(baseDir?: string, options?: RouterCollectorOptions);
208
- protected init(): Promise<void>;
209
- getRoutePriorityList(): Promise<RouterPriority[]>;
210
- getRouterTable(): Promise<Map<string, RouterInfo[]>>;
211
- getFlattenRouterTable(): Promise<RouterInfo[]>;
199
+ protected checkDuplicateAndPush(prefix: any, routerInfo: RouterInfo): void;
212
200
  }
213
201
  //# sourceMappingURL=webRouterService.d.ts.map
@@ -9,14 +9,11 @@ var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.WebRouterCollector = exports.MidwayWebRouterService = void 0;
12
+ exports.MidwayWebRouterService = void 0;
13
13
  const decorator_1 = require("@midwayjs/decorator");
14
14
  const util_1 = require("../util");
15
15
  const error_1 = require("../error");
16
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");
20
17
  const debug = util.debuglog('midway:debug');
21
18
  let MidwayWebRouterService = class MidwayWebRouterService {
22
19
  constructor(options = {}) {
@@ -26,17 +23,17 @@ let MidwayWebRouterService = class MidwayWebRouterService {
26
23
  this.routesPriority = [];
27
24
  }
28
25
  async analyze() {
26
+ this.analyzeController();
27
+ this.sortPrefixAndRouter();
28
+ }
29
+ analyzeController() {
29
30
  const controllerModules = (0, decorator_1.listModule)(decorator_1.CONTROLLER_KEY);
30
31
  for (const module of controllerModules) {
31
32
  const controllerOption = (0, decorator_1.getClassMetadata)(decorator_1.CONTROLLER_KEY, module);
32
33
  this.addController(module, controllerOption, this.options.includeFunctionRouter);
33
34
  }
34
- if (this.options.includeFunctionRouter) {
35
- const fnModules = (0, decorator_1.listModule)(decorator_1.FUNC_KEY);
36
- for (const module of fnModules) {
37
- this.collectFunctionRoute(module, this.options.includeFunctionRouter);
38
- }
39
- }
35
+ }
36
+ sortPrefixAndRouter() {
40
37
  // filter empty prefix
41
38
  this.routesPriority = this.routesPriority.filter(item => {
42
39
  const prefixList = this.routes.get(item.prefix);
@@ -57,25 +54,6 @@ let MidwayWebRouterService = class MidwayWebRouterService {
57
54
  this.routesPriority = this.routesPriority.sort((routeA, routeB) => {
58
55
  return routeB.prefix.length - routeA.prefix.length;
59
56
  });
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
- }
79
57
  }
80
58
  /**
81
59
  * dynamically add a controller
@@ -113,6 +91,15 @@ let MidwayWebRouterService = class MidwayWebRouterService {
113
91
  routerModule: controllerClz,
114
92
  });
115
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
+ }
116
103
  // set ignorePrefix
117
104
  if (!this.routes.has(ignorePrefix)) {
118
105
  this.routes.set(ignorePrefix, []);
@@ -169,19 +156,8 @@ let MidwayWebRouterService = class MidwayWebRouterService {
169
156
  * @param routerFunction
170
157
  * @param routerInfoOption
171
158
  */
172
- addRouter(routerPath, routerFunction, routerInfoOption) {
173
- this.checkDuplicateAndPush('/', Object.assign(routerInfoOption, {
174
- method: routerFunction,
175
- url: routerPath,
176
- }));
177
- }
178
- collectFunctionRoute(module, functionMeta = false) {
179
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
180
- // serverlessTrigger metadata
181
- const webRouterInfo = (0, decorator_1.getClassMetadata)(decorator_1.FUNC_KEY, module);
182
- const controllerId = (0, decorator_1.getProviderName)(module);
183
- const id = (0, decorator_1.getProviderUUId)(module);
184
- const prefix = '/';
159
+ addRouter(routerFunction, routerInfoOption) {
160
+ const prefix = routerInfoOption.prefix || '';
185
161
  if (!this.routes.has(prefix)) {
186
162
  this.routes.set(prefix, []);
187
163
  this.routesPriority.push({
@@ -189,78 +165,13 @@ let MidwayWebRouterService = class MidwayWebRouterService {
189
165
  priority: -999,
190
166
  middleware: [],
191
167
  routerOptions: {},
192
- controllerId,
193
- routerModule: module,
168
+ controllerId: undefined,
169
+ routerModule: undefined,
194
170
  });
195
171
  }
196
- for (const webRouter of webRouterInfo) {
197
- // 新的 @ServerlessTrigger 写法
198
- if ((_a = webRouter['metadata']) === null || _a === void 0 ? void 0 : _a['path']) {
199
- const routeArgsInfo = (0, decorator_1.getPropertyDataFromClass)(decorator_1.WEB_ROUTER_PARAM_KEY, module, webRouter['methodName']) || [];
200
- const routerResponseData = (0, decorator_1.getPropertyMetadata)(decorator_1.WEB_RESPONSE_KEY, module, webRouter['methodName']) || [];
201
- // 新 http/api gateway 函数
202
- const data = {
203
- id,
204
- prefix,
205
- routerName: '',
206
- url: webRouter['metadata']['path'],
207
- requestMethod: (_c = (_b = webRouter['metadata']) === null || _b === void 0 ? void 0 : _b['method']) !== null && _c !== void 0 ? _c : 'get',
208
- method: webRouter['methodName'],
209
- description: '',
210
- summary: '',
211
- handlerName: `${controllerId}.${webRouter['methodName']}`,
212
- funcHandlerName: `${controllerId}.${webRouter['methodName']}`,
213
- controllerId,
214
- middleware: ((_d = webRouter['metadata']) === null || _d === void 0 ? void 0 : _d['middleware']) || [],
215
- controllerMiddleware: [],
216
- requestMetadata: routeArgsInfo,
217
- responseMetadata: routerResponseData,
218
- };
219
- if (functionMeta) {
220
- const functionMeta = (0, decorator_1.getPropertyMetadata)(decorator_1.SERVERLESS_FUNC_KEY, module, webRouter['methodName']) || {};
221
- const functionName = (_f = (_e = functionMeta['functionName']) !== null && _e !== void 0 ? _e : webRouter['functionName']) !== null && _f !== void 0 ? _f : createFunctionName(module, webRouter['methodName']);
222
- data.functionName = functionName;
223
- data.functionTriggerName = webRouter['type'];
224
- data.functionTriggerMetadata = webRouter['metadata'];
225
- data.functionMetadata = {
226
- functionName,
227
- ...functionMeta,
228
- };
229
- }
230
- this.checkDuplicateAndPush(prefix, data);
231
- }
232
- else {
233
- if (functionMeta) {
234
- const functionMeta = (0, decorator_1.getPropertyMetadata)(decorator_1.SERVERLESS_FUNC_KEY, module, webRouter['methodName']) || {};
235
- const functionName = (_h = (_g = functionMeta['functionName']) !== null && _g !== void 0 ? _g : webRouter['functionName']) !== null && _h !== void 0 ? _h : createFunctionName(module, webRouter['methodName']);
236
- // 其他类型的函数
237
- this.checkDuplicateAndPush(prefix, {
238
- id,
239
- prefix,
240
- routerName: '',
241
- url: '',
242
- requestMethod: '',
243
- method: webRouter['methodName'],
244
- description: '',
245
- summary: '',
246
- handlerName: `${controllerId}.${webRouter['methodName']}`,
247
- funcHandlerName: `${controllerId}.${webRouter['methodName']}`,
248
- controllerId,
249
- middleware: ((_j = webRouter['metadata']) === null || _j === void 0 ? void 0 : _j['middleware']) || [],
250
- controllerMiddleware: [],
251
- requestMetadata: [],
252
- responseMetadata: [],
253
- functionName,
254
- functionTriggerName: webRouter['type'],
255
- functionTriggerMetadata: webRouter['metadata'],
256
- functionMetadata: {
257
- functionName,
258
- ...functionMeta,
259
- },
260
- });
261
- }
262
- }
263
- }
172
+ this.checkDuplicateAndPush(prefix, Object.assign(routerInfoOption, {
173
+ method: routerFunction,
174
+ }));
264
175
  }
265
176
  sortRouter(urlMatchList) {
266
177
  // 1. 绝对路径规则优先级最高如 /ab/cb/e
@@ -369,49 +280,4 @@ MidwayWebRouterService = __decorate([
369
280
  __metadata("design:paramtypes", [Object])
370
281
  ], MidwayWebRouterService);
371
282
  exports.MidwayWebRouterService = MidwayWebRouterService;
372
- function createFunctionName(target, functionName) {
373
- return (0, decorator_1.getProviderName)(target).replace(/[:#]/g, '-') + '-' + functionName;
374
- }
375
- /**
376
- * @deprecated use built-in MidwayWebRouterService first
377
- */
378
- class WebRouterCollector {
379
- constructor(baseDir = '', options = {}) {
380
- this.baseDir = baseDir;
381
- this.options = options;
382
- }
383
- async init() {
384
- if (!this.proxy) {
385
- if (this.baseDir) {
386
- const container = new container_1.MidwayContainer();
387
- (0, decorator_1.bindContainer)(container);
388
- container.setFileDetector(new fileDetector_1.DirectoryFileDetector({
389
- loadDir: this.baseDir,
390
- }));
391
- await container.ready();
392
- }
393
- if ((0, contextUtil_1.getCurrentMainFramework)()) {
394
- this.proxy = await (0, contextUtil_1.getCurrentMainFramework)()
395
- .getApplicationContext()
396
- .getAsync(MidwayWebRouterService, [this.options]);
397
- }
398
- else {
399
- this.proxy = new MidwayWebRouterService(this.options);
400
- }
401
- }
402
- }
403
- async getRoutePriorityList() {
404
- await this.init();
405
- return this.proxy.getRoutePriorityList();
406
- }
407
- async getRouterTable() {
408
- await this.init();
409
- return this.proxy.getRouterTable();
410
- }
411
- async getFlattenRouterTable() {
412
- await this.init();
413
- return this.proxy.getFlattenRouterTable();
414
- }
415
- }
416
- exports.WebRouterCollector = WebRouterCollector;
417
283
  //# 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.
@@ -96,6 +97,7 @@ function prepareGlobalApplicationContext(globalOptions) {
96
97
  applicationContext.bindClass(_1.MidwayLifeCycleService);
97
98
  applicationContext.bindClass(_1.MidwayMockService);
98
99
  applicationContext.bindClass(_1.MidwayWebRouterService);
100
+ applicationContext.bindClass(slsFunctionService_1.MidwayServerlessFunctionService);
99
101
  // bind preload module
100
102
  if (globalOptions.preloadModules && globalOptions.preloadModules.length) {
101
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.2",
3
+ "version": "3.4.0-beta.5",
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.2",
24
+ "@midwayjs/decorator": "^3.4.0-beta.5",
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": "a61721d3946b30fd4cac183265edcd99b31ac72b"
48
+ "gitHead": "d84d1c77aed1fd973d002ab65cd0adeadb7924a6"
49
49
  }