@midwayjs/core 3.4.0-beta.3 → 3.4.0-beta.6

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
  }
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);
@@ -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,242 @@
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
+ compileUrlPattern: true,
138
+ });
139
+ }
140
+ addServerlessFunction(func, triggerOptions, functionOptions = {}) {
141
+ var _a, _b;
142
+ const prefix = '';
143
+ if (!this.routes.has(prefix)) {
144
+ this.routes.set(prefix, []);
145
+ this.routesPriority.push({
146
+ prefix,
147
+ priority: -999,
148
+ middleware: [],
149
+ routerOptions: {},
150
+ controllerId: undefined,
151
+ routerModule: undefined,
152
+ });
153
+ }
154
+ const functionName = (_a = triggerOptions.functionName) !== null && _a !== void 0 ? _a : functionOptions.functionName;
155
+ this.checkDuplicateAndPush(prefix, {
156
+ id: null,
157
+ method: func,
158
+ url: triggerOptions.metadata['path'] || '',
159
+ requestMethod: triggerOptions.metadata['method'] || '',
160
+ description: '',
161
+ summary: '',
162
+ handlerName: '',
163
+ funcHandlerName: triggerOptions.handlerName || functionOptions.handlerName,
164
+ controllerId: '',
165
+ middleware: ((_b = triggerOptions.metadata) === null || _b === void 0 ? void 0 : _b.middleware) || [],
166
+ controllerMiddleware: [],
167
+ requestMetadata: [],
168
+ responseMetadata: [],
169
+ functionName,
170
+ functionTriggerName: triggerOptions.metadata.name,
171
+ functionTriggerMetadata: triggerOptions.metadata,
172
+ functionMetadata: {
173
+ functionName,
174
+ ...functionOptions,
175
+ },
176
+ });
177
+ }
178
+ };
179
+ MidwayServerlessFunctionService = __decorate([
180
+ (0, decorator_1.Provide)(),
181
+ (0, decorator_1.Scope)(decorator_1.ScopeEnum.Singleton),
182
+ __metadata("design:paramtypes", [Object])
183
+ ], MidwayServerlessFunctionService);
184
+ exports.MidwayServerlessFunctionService = MidwayServerlessFunctionService;
185
+ function createFunctionName(target, functionName) {
186
+ return (0, decorator_1.getProviderName)(target).replace(/[:#]/g, '-') + '-' + functionName;
187
+ }
188
+ /**
189
+ * @deprecated use built-in MidwayWebRouterService first
190
+ */
191
+ class WebRouterCollector {
192
+ constructor(baseDir = '', options = {}) {
193
+ this.baseDir = baseDir;
194
+ this.options = options;
195
+ }
196
+ async init() {
197
+ if (!this.proxy) {
198
+ if (this.baseDir) {
199
+ const container = new container_1.MidwayContainer();
200
+ (0, decorator_1.bindContainer)(container);
201
+ container.setFileDetector(new fileDetector_1.DirectoryFileDetector({
202
+ loadDir: this.baseDir,
203
+ }));
204
+ await container.ready();
205
+ }
206
+ if (this.options.includeFunctionRouter) {
207
+ if ((0, contextUtil_1.getCurrentMainFramework)()) {
208
+ this.proxy = await (0, contextUtil_1.getCurrentMainFramework)()
209
+ .getApplicationContext()
210
+ .getAsync(MidwayServerlessFunctionService, [this.options]);
211
+ }
212
+ else {
213
+ this.proxy = new MidwayServerlessFunctionService(this.options);
214
+ }
215
+ }
216
+ else {
217
+ if ((0, contextUtil_1.getCurrentMainFramework)()) {
218
+ this.proxy = await (0, contextUtil_1.getCurrentMainFramework)()
219
+ .getApplicationContext()
220
+ .getAsync(webRouterService_1.MidwayWebRouterService, [this.options]);
221
+ }
222
+ else {
223
+ this.proxy = new webRouterService_1.MidwayWebRouterService(this.options);
224
+ }
225
+ }
226
+ }
227
+ }
228
+ async getRoutePriorityList() {
229
+ await this.init();
230
+ return this.proxy.getRoutePriorityList();
231
+ }
232
+ async getRouterTable() {
233
+ await this.init();
234
+ return this.proxy.getRouterTable();
235
+ }
236
+ async getFlattenRouterTable() {
237
+ await this.init();
238
+ return this.proxy.getFlattenRouterTable();
239
+ }
240
+ }
241
+ exports.WebRouterCollector = WebRouterCollector;
242
+ //# sourceMappingURL=slsFunctionService.js.map
@@ -73,8 +73,12 @@ export interface RouterInfo {
73
73
  * serverless function metadata
74
74
  */
75
75
  functionMetadata?: any;
76
+ /**
77
+ * pattern after path-regexp compile
78
+ */
79
+ urlCompiledPattern?: RegExp;
76
80
  }
77
- export declare type DynamicRouterInfo = Omit<RouterInfo, 'id' | 'url' | 'prefix' | 'method' | 'controllerId' | 'controllerMiddleware' | 'responseMetadata'>;
81
+ export declare type DynamicRouterInfo = Omit<RouterInfo, 'id' | 'method' | 'controllerId' | 'controllerMiddleware' | 'responseMetadata'>;
78
82
  export interface RouterPriority {
79
83
  prefix: string;
80
84
  priority: number;
@@ -94,9 +98,13 @@ export declare class MidwayWebRouterService {
94
98
  readonly options: RouterCollectorOptions;
95
99
  private isReady;
96
100
  protected routes: Map<string, RouterInfo[]>;
97
- private routesPriority;
101
+ protected routesPriority: RouterPriority[];
102
+ private cachedFlattenRouteList;
103
+ private includeCompileUrlPattern;
98
104
  constructor(options?: RouterCollectorOptions);
99
- private analyze;
105
+ protected analyze(): Promise<void>;
106
+ protected analyzeController(): void;
107
+ protected sortPrefixAndRouter(): void;
100
108
  /**
101
109
  * dynamically add a controller
102
110
  * @param controllerClz
@@ -110,8 +118,7 @@ export declare class MidwayWebRouterService {
110
118
  * @param routerFunction
111
119
  * @param routerInfoOption
112
120
  */
113
- addRouter(routerPath: string | RegExp, routerFunction: (...args: any[]) => void, routerInfoOption: DynamicRouterInfo): void;
114
- protected collectFunctionRoute(module: any, functionMeta?: boolean): void;
121
+ addRouter(routerFunction: (...args: any[]) => void, routerInfoOption: DynamicRouterInfo): void;
115
122
  sortRouter(urlMatchList: RouterInfo[]): {
116
123
  _pureRouter: string;
117
124
  _level: number;
@@ -191,23 +198,18 @@ export declare class MidwayWebRouterService {
191
198
  * serverless function metadata
192
199
  */
193
200
  functionMetadata?: any;
201
+ /**
202
+ * pattern after path-regexp compile
203
+ */
204
+ urlCompiledPattern?: RegExp;
194
205
  }[];
195
206
  getRoutePriorityList(): Promise<RouterPriority[]>;
196
207
  getRouterTable(): Promise<Map<string, RouterInfo[]>>;
197
- 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[]>;
208
+ getFlattenRouterTable(options?: {
209
+ compileUrlPattern?: boolean;
210
+ noCache?: boolean;
211
+ }): Promise<RouterInfo[]>;
212
+ getMatchedRouterInfo(routerUrl: string, method: string): Promise<RouterInfo | undefined>;
213
+ protected checkDuplicateAndPush(prefix: any, routerInfo: RouterInfo): void;
212
214
  }
213
215
  //# sourceMappingURL=webRouterService.d.ts.map
@@ -9,14 +9,12 @@ 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");
17
+ const pathToRegexp_1 = require("../util/pathToRegexp");
20
18
  const debug = util.debuglog('midway:debug');
21
19
  let MidwayWebRouterService = class MidwayWebRouterService {
22
20
  constructor(options = {}) {
@@ -24,19 +22,20 @@ let MidwayWebRouterService = class MidwayWebRouterService {
24
22
  this.isReady = false;
25
23
  this.routes = new Map();
26
24
  this.routesPriority = [];
25
+ this.includeCompileUrlPattern = false;
27
26
  }
28
27
  async analyze() {
28
+ this.analyzeController();
29
+ this.sortPrefixAndRouter();
30
+ }
31
+ analyzeController() {
29
32
  const controllerModules = (0, decorator_1.listModule)(decorator_1.CONTROLLER_KEY);
30
33
  for (const module of controllerModules) {
31
34
  const controllerOption = (0, decorator_1.getClassMetadata)(decorator_1.CONTROLLER_KEY, module);
32
35
  this.addController(module, controllerOption, this.options.includeFunctionRouter);
33
36
  }
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
- }
37
+ }
38
+ sortPrefixAndRouter() {
40
39
  // filter empty prefix
41
40
  this.routesPriority = this.routesPriority.filter(item => {
42
41
  const prefixList = this.routes.get(item.prefix);
@@ -57,25 +56,6 @@ let MidwayWebRouterService = class MidwayWebRouterService {
57
56
  this.routesPriority = this.routesPriority.sort((routeA, routeB) => {
58
57
  return routeB.prefix.length - routeA.prefix.length;
59
58
  });
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
59
  }
80
60
  /**
81
61
  * dynamically add a controller
@@ -178,19 +158,8 @@ let MidwayWebRouterService = class MidwayWebRouterService {
178
158
  * @param routerFunction
179
159
  * @param routerInfoOption
180
160
  */
181
- addRouter(routerPath, routerFunction, routerInfoOption) {
182
- this.checkDuplicateAndPush('/', Object.assign(routerInfoOption, {
183
- method: routerFunction,
184
- url: routerPath,
185
- }));
186
- }
187
- collectFunctionRoute(module, functionMeta = false) {
188
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
189
- // serverlessTrigger metadata
190
- const webRouterInfo = (0, decorator_1.getClassMetadata)(decorator_1.FUNC_KEY, module);
191
- const controllerId = (0, decorator_1.getProviderName)(module);
192
- const id = (0, decorator_1.getProviderUUId)(module);
193
- const prefix = '/';
161
+ addRouter(routerFunction, routerInfoOption) {
162
+ const prefix = routerInfoOption.prefix || '';
194
163
  if (!this.routes.has(prefix)) {
195
164
  this.routes.set(prefix, []);
196
165
  this.routesPriority.push({
@@ -198,78 +167,13 @@ let MidwayWebRouterService = class MidwayWebRouterService {
198
167
  priority: -999,
199
168
  middleware: [],
200
169
  routerOptions: {},
201
- controllerId,
202
- routerModule: module,
170
+ controllerId: undefined,
171
+ routerModule: undefined,
203
172
  });
204
173
  }
205
- for (const webRouter of webRouterInfo) {
206
- // 新的 @ServerlessTrigger 写法
207
- if ((_a = webRouter['metadata']) === null || _a === void 0 ? void 0 : _a['path']) {
208
- const routeArgsInfo = (0, decorator_1.getPropertyDataFromClass)(decorator_1.WEB_ROUTER_PARAM_KEY, module, webRouter['methodName']) || [];
209
- const routerResponseData = (0, decorator_1.getPropertyMetadata)(decorator_1.WEB_RESPONSE_KEY, module, webRouter['methodName']) || [];
210
- // 新 http/api gateway 函数
211
- const data = {
212
- id,
213
- prefix,
214
- routerName: '',
215
- url: webRouter['metadata']['path'],
216
- requestMethod: (_c = (_b = webRouter['metadata']) === null || _b === void 0 ? void 0 : _b['method']) !== null && _c !== void 0 ? _c : 'get',
217
- method: webRouter['methodName'],
218
- description: '',
219
- summary: '',
220
- handlerName: `${controllerId}.${webRouter['methodName']}`,
221
- funcHandlerName: `${controllerId}.${webRouter['methodName']}`,
222
- controllerId,
223
- middleware: ((_d = webRouter['metadata']) === null || _d === void 0 ? void 0 : _d['middleware']) || [],
224
- controllerMiddleware: [],
225
- requestMetadata: routeArgsInfo,
226
- responseMetadata: routerResponseData,
227
- };
228
- if (functionMeta) {
229
- const functionMeta = (0, decorator_1.getPropertyMetadata)(decorator_1.SERVERLESS_FUNC_KEY, module, webRouter['methodName']) || {};
230
- const functionName = (_f = (_e = functionMeta['functionName']) !== null && _e !== void 0 ? _e : webRouter['functionName']) !== null && _f !== void 0 ? _f : createFunctionName(module, webRouter['methodName']);
231
- data.functionName = functionName;
232
- data.functionTriggerName = webRouter['type'];
233
- data.functionTriggerMetadata = webRouter['metadata'];
234
- data.functionMetadata = {
235
- functionName,
236
- ...functionMeta,
237
- };
238
- }
239
- this.checkDuplicateAndPush(prefix, data);
240
- }
241
- else {
242
- if (functionMeta) {
243
- const functionMeta = (0, decorator_1.getPropertyMetadata)(decorator_1.SERVERLESS_FUNC_KEY, module, webRouter['methodName']) || {};
244
- const functionName = (_h = (_g = functionMeta['functionName']) !== null && _g !== void 0 ? _g : webRouter['functionName']) !== null && _h !== void 0 ? _h : createFunctionName(module, webRouter['methodName']);
245
- // 其他类型的函数
246
- this.checkDuplicateAndPush(prefix, {
247
- id,
248
- prefix,
249
- routerName: '',
250
- url: '',
251
- requestMethod: '',
252
- method: webRouter['methodName'],
253
- description: '',
254
- summary: '',
255
- handlerName: `${controllerId}.${webRouter['methodName']}`,
256
- funcHandlerName: `${controllerId}.${webRouter['methodName']}`,
257
- controllerId,
258
- middleware: ((_j = webRouter['metadata']) === null || _j === void 0 ? void 0 : _j['middleware']) || [],
259
- controllerMiddleware: [],
260
- requestMetadata: [],
261
- responseMetadata: [],
262
- functionName,
263
- functionTriggerName: webRouter['type'],
264
- functionTriggerMetadata: webRouter['metadata'],
265
- functionMetadata: {
266
- functionName,
267
- ...functionMeta,
268
- },
269
- });
270
- }
271
- }
272
- }
174
+ this.checkDuplicateAndPush(prefix, Object.assign(routerInfoOption, {
175
+ method: routerFunction,
176
+ }));
273
177
  }
274
178
  sortRouter(urlMatchList) {
275
179
  // 1. 绝对路径规则优先级最高如 /ab/cb/e
@@ -347,7 +251,21 @@ let MidwayWebRouterService = class MidwayWebRouterService {
347
251
  }
348
252
  return this.routes;
349
253
  }
350
- async getFlattenRouterTable() {
254
+ async getFlattenRouterTable(options = {}) {
255
+ if (this.cachedFlattenRouteList && !options.noCache) {
256
+ if (options.compileUrlPattern && !this.includeCompileUrlPattern) {
257
+ this.includeCompileUrlPattern = true;
258
+ // attach match pattern function
259
+ for (const item of this.cachedFlattenRouteList) {
260
+ if (item.url) {
261
+ item.urlCompiledPattern = (0, pathToRegexp_1.pathToRegexp)(item.url, [], {
262
+ end: false,
263
+ });
264
+ }
265
+ }
266
+ }
267
+ return this.cachedFlattenRouteList;
268
+ }
351
269
  if (!this.isReady) {
352
270
  await this.analyze();
353
271
  this.isReady = true;
@@ -356,8 +274,34 @@ let MidwayWebRouterService = class MidwayWebRouterService {
356
274
  for (const routerPriority of this.routesPriority) {
357
275
  routeArr = routeArr.concat(this.routes.get(routerPriority.prefix));
358
276
  }
277
+ if (options.compileUrlPattern) {
278
+ this.includeCompileUrlPattern = true;
279
+ // attach match pattern function
280
+ for (const item of routeArr) {
281
+ item.urlCompiledPattern = (0, pathToRegexp_1.pathToRegexp)(item.url, [], {
282
+ end: false,
283
+ });
284
+ }
285
+ }
286
+ this.cachedFlattenRouteList = routeArr;
359
287
  return routeArr;
360
288
  }
289
+ async getMatchedRouterInfo(routerUrl, method) {
290
+ const routes = await this.getFlattenRouterTable({
291
+ compileUrlPattern: true,
292
+ });
293
+ let matchedRouterInfo;
294
+ for (const item of routes) {
295
+ if (item.urlCompiledPattern) {
296
+ if (method.toUpperCase() === item['requestMethod'].toUpperCase() &&
297
+ item.urlCompiledPattern.test(routerUrl)) {
298
+ matchedRouterInfo = item;
299
+ break;
300
+ }
301
+ }
302
+ }
303
+ return matchedRouterInfo;
304
+ }
361
305
  checkDuplicateAndPush(prefix, routerInfo) {
362
306
  const prefixList = this.routes.get(prefix);
363
307
  const matched = prefixList.filter(item => {
@@ -378,49 +322,4 @@ MidwayWebRouterService = __decorate([
378
322
  __metadata("design:paramtypes", [Object])
379
323
  ], MidwayWebRouterService);
380
324
  exports.MidwayWebRouterService = MidwayWebRouterService;
381
- function createFunctionName(target, functionName) {
382
- return (0, decorator_1.getProviderName)(target).replace(/[:#]/g, '-') + '-' + functionName;
383
- }
384
- /**
385
- * @deprecated use built-in MidwayWebRouterService first
386
- */
387
- class WebRouterCollector {
388
- constructor(baseDir = '', options = {}) {
389
- this.baseDir = baseDir;
390
- this.options = options;
391
- }
392
- async init() {
393
- if (!this.proxy) {
394
- if (this.baseDir) {
395
- const container = new container_1.MidwayContainer();
396
- (0, decorator_1.bindContainer)(container);
397
- container.setFileDetector(new fileDetector_1.DirectoryFileDetector({
398
- loadDir: this.baseDir,
399
- }));
400
- await container.ready();
401
- }
402
- if ((0, contextUtil_1.getCurrentMainFramework)()) {
403
- this.proxy = await (0, contextUtil_1.getCurrentMainFramework)()
404
- .getApplicationContext()
405
- .getAsync(MidwayWebRouterService, [this.options]);
406
- }
407
- else {
408
- this.proxy = new MidwayWebRouterService(this.options);
409
- }
410
- }
411
- }
412
- async getRoutePriorityList() {
413
- await this.init();
414
- return this.proxy.getRoutePriorityList();
415
- }
416
- async getRouterTable() {
417
- await this.init();
418
- return this.proxy.getRouterTable();
419
- }
420
- async getFlattenRouterTable() {
421
- await this.init();
422
- return this.proxy.getFlattenRouterTable();
423
- }
424
- }
425
- exports.WebRouterCollector = WebRouterCollector;
426
325
  //# 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) {
@@ -1,6 +1,12 @@
1
1
  /**
2
2
  * this file fork from path-to-regexp package v1.8.0
3
3
  */
4
+ export interface PathToRegexpOptions {
5
+ end?: boolean;
6
+ strict?: boolean;
7
+ delimiter?: string;
8
+ sensitive?: boolean;
9
+ }
4
10
  /**
5
11
  * Normalize the given path string, returning a regular expression.
6
12
  *
@@ -13,5 +19,6 @@
13
19
  * @param {Object=} options
14
20
  * @return {!RegExp}
15
21
  */
16
- export declare function pathToRegexp(path: any, keys: any, options: any): any;
22
+ export declare function pathToRegexp(path: string | RegExp | Array<string>, options?: PathToRegexpOptions): RegExp;
23
+ export declare function pathToRegexp(path: string | RegExp | Array<string>, keys: Array<string>, options?: PathToRegexpOptions): RegExp;
17
24
  //# sourceMappingURL=pathToRegexp.d.ts.map
@@ -246,18 +246,6 @@ function tokensToRegExp(tokens, keys, options) {
246
246
  }
247
247
  return attachKeys(new RegExp('^' + route, flags(options)), keys);
248
248
  }
249
- /**
250
- * Normalize the given path string, returning a regular expression.
251
- *
252
- * An empty array can be passed in for the keys, which will hold the
253
- * placeholder key descriptions. For example, using `/user/:id`, `keys` will
254
- * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
255
- *
256
- * @param {(string|RegExp|Array)} path
257
- * @param {(Array|Object)=} keys
258
- * @param {Object=} options
259
- * @return {!RegExp}
260
- */
261
249
  function pathToRegexp(path, keys, options) {
262
250
  if (!Array.isArray(keys)) {
263
251
  options = /** @type {!Object} */ keys || options;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/core",
3
- "version": "3.4.0-beta.3",
3
+ "version": "3.4.0-beta.6",
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.3",
24
+ "@midwayjs/decorator": "^3.4.0-beta.6",
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": "ddbff5c3da5d908953cc691a8e5de4f0197de365"
48
+ "gitHead": "8e187c4593d4832de32b6745af3e195f6b90816c"
49
49
  }