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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/baseFramework.d.ts +3 -0
  2. package/dist/baseFramework.js +32 -13
  3. package/dist/common/asyncContextManager.d.ts +61 -0
  4. package/dist/common/asyncContextManager.js +63 -0
  5. package/dist/common/dataSourceManager.d.ts +8 -1
  6. package/dist/common/dataSourceManager.js +61 -3
  7. package/dist/common/webGenerator.d.ts +4 -3
  8. package/dist/common/webGenerator.js +24 -15
  9. package/dist/config/config.default.d.ts +3 -0
  10. package/dist/config/config.default.js +3 -0
  11. package/dist/error/base.d.ts +1 -1
  12. package/dist/error/base.js +6 -1
  13. package/dist/error/framework.d.ts +4 -0
  14. package/dist/error/framework.js +8 -1
  15. package/dist/error/http.js +16 -16
  16. package/dist/index.d.ts +4 -3
  17. package/dist/index.js +10 -4
  18. package/dist/interface.d.ts +5 -4
  19. package/dist/interface.js +3 -1
  20. package/dist/service/configService.js +7 -4
  21. package/dist/service/frameworkService.js +7 -6
  22. package/dist/service/middlewareService.js +13 -5
  23. package/dist/service/slsFunctionService.d.ts +25 -0
  24. package/dist/service/slsFunctionService.js +242 -0
  25. package/dist/{common/webRouterCollector.d.ts → service/webRouterService.d.ts} +87 -36
  26. package/dist/{common/webRouterCollector.js → service/webRouterService.js} +121 -116
  27. package/dist/setup.js +3 -0
  28. package/dist/util/contextUtil.d.ts +2 -0
  29. package/dist/util/contextUtil.js +6 -1
  30. package/dist/util/index.js +1 -1
  31. package/dist/util/pathToRegexp.d.ts +113 -7
  32. package/dist/util/pathToRegexp.js +326 -205
  33. package/package.json +3 -3
  34. package/dist/common/triggerCollector.d.ts +0 -8
  35. package/dist/common/triggerCollector.js +0 -37
@@ -57,7 +57,7 @@ var HttpStatus;
57
57
  * 400 http error, Means that the request can be fulfilled because of the bad syntax.
58
58
  */
59
59
  class BadRequestError extends base_1.MidwayHttpError {
60
- constructor(resOrMessage = 'Bad Request') {
60
+ constructor(resOrMessage) {
61
61
  super(resOrMessage, HttpStatus.BAD_REQUEST);
62
62
  }
63
63
  }
@@ -66,7 +66,7 @@ exports.BadRequestError = BadRequestError;
66
66
  * 401 http error, Means that the request was legal, but the server is rejecting to answer it. For the use when authentication is required and has failed or has not yet been provided.
67
67
  */
68
68
  class UnauthorizedError extends base_1.MidwayHttpError {
69
- constructor(resOrMessage = 'Unauthorized') {
69
+ constructor(resOrMessage) {
70
70
  super(resOrMessage, HttpStatus.UNAUTHORIZED);
71
71
  }
72
72
  }
@@ -75,7 +75,7 @@ exports.UnauthorizedError = UnauthorizedError;
75
75
  * 4o4 http error, Means that the requested page cannot be found at the moment, but it may be available again in the future.
76
76
  */
77
77
  class NotFoundError extends base_1.MidwayHttpError {
78
- constructor(resOrMessage = 'Not Found') {
78
+ constructor(resOrMessage) {
79
79
  super(resOrMessage, HttpStatus.NOT_FOUND);
80
80
  }
81
81
  }
@@ -84,7 +84,7 @@ exports.NotFoundError = NotFoundError;
84
84
  * 403 http error, Means that the request is legal, but the server is rejecting to answer it.
85
85
  */
86
86
  class ForbiddenError extends base_1.MidwayHttpError {
87
- constructor(resOrMessage = 'Forbidden') {
87
+ constructor(resOrMessage) {
88
88
  super(resOrMessage, HttpStatus.FORBIDDEN);
89
89
  }
90
90
  }
@@ -93,7 +93,7 @@ exports.ForbiddenError = ForbiddenError;
93
93
  * 406 http error, Means that the server can only generate an answer which the client doesn't accept.
94
94
  */
95
95
  class NotAcceptableError extends base_1.MidwayHttpError {
96
- constructor(resOrMessage = 'Not Acceptable') {
96
+ constructor(resOrMessage) {
97
97
  super(resOrMessage, HttpStatus.NOT_ACCEPTABLE);
98
98
  }
99
99
  }
@@ -102,7 +102,7 @@ exports.NotAcceptableError = NotAcceptableError;
102
102
  * 408 http error, Means that the server timed out waiting for the request.
103
103
  */
104
104
  class RequestTimeoutError extends base_1.MidwayHttpError {
105
- constructor(resOrMessage = 'Request Timeout') {
105
+ constructor(resOrMessage) {
106
106
  super(resOrMessage, HttpStatus.REQUEST_TIMEOUT);
107
107
  }
108
108
  }
@@ -111,7 +111,7 @@ exports.RequestTimeoutError = RequestTimeoutError;
111
111
  * 409 http error, Means that the request cannot be completed, because of a conflict in the request.
112
112
  */
113
113
  class ConflictError extends base_1.MidwayHttpError {
114
- constructor(resOrMessage = 'Conflict') {
114
+ constructor(resOrMessage) {
115
115
  super(resOrMessage, HttpStatus.CONFLICT);
116
116
  }
117
117
  }
@@ -120,7 +120,7 @@ exports.ConflictError = ConflictError;
120
120
  * 410 http error, Means that the requested page is not available anymore.
121
121
  */
122
122
  class GoneError extends base_1.MidwayHttpError {
123
- constructor(resOrMessage = 'Gone') {
123
+ constructor(resOrMessage) {
124
124
  super(resOrMessage, HttpStatus.GONE);
125
125
  }
126
126
  }
@@ -129,7 +129,7 @@ exports.GoneError = GoneError;
129
129
  * 413 http error, Means that the request entity is too large and that's why the server won't accept the request.
130
130
  */
131
131
  class PayloadTooLargeError extends base_1.MidwayHttpError {
132
- constructor(resOrMessage = 'Request Entity Too Large') {
132
+ constructor(resOrMessage) {
133
133
  super(resOrMessage, HttpStatus.PAYLOAD_TOO_LARGE);
134
134
  }
135
135
  }
@@ -138,13 +138,13 @@ exports.PayloadTooLargeError = PayloadTooLargeError;
138
138
  * 415 http error, Means that the media type is not supported and that's why the server won't accept the request.
139
139
  */
140
140
  class UnsupportedMediaTypeError extends base_1.MidwayHttpError {
141
- constructor(resOrMessage = 'Unsupported Media Type') {
141
+ constructor(resOrMessage) {
142
142
  super(resOrMessage, HttpStatus.UNSUPPORTED_MEDIA_TYPE);
143
143
  }
144
144
  }
145
145
  exports.UnsupportedMediaTypeError = UnsupportedMediaTypeError;
146
146
  class UnprocessableEntityError extends base_1.MidwayHttpError {
147
- constructor(resOrMessage = 'Unprocessable Entity') {
147
+ constructor(resOrMessage) {
148
148
  super(resOrMessage, HttpStatus.UNPROCESSABLE_ENTITY);
149
149
  }
150
150
  }
@@ -153,7 +153,7 @@ exports.UnprocessableEntityError = UnprocessableEntityError;
153
153
  * 500 http error, Is a generic error and users receive this error message when there is no more suitable specific message.
154
154
  */
155
155
  class InternalServerErrorError extends base_1.MidwayHttpError {
156
- constructor(resOrMessage = 'Internal Server Error') {
156
+ constructor(resOrMessage) {
157
157
  super(resOrMessage, HttpStatus.INTERNAL_SERVER_ERROR);
158
158
  }
159
159
  }
@@ -162,7 +162,7 @@ exports.InternalServerErrorError = InternalServerErrorError;
162
162
  * 501 http error, Means that the server doesn't recognize the request method or it lacks the ability to fulfill the request.
163
163
  */
164
164
  class NotImplementedError extends base_1.MidwayHttpError {
165
- constructor(resOrMessage = 'Not Implemented') {
165
+ constructor(resOrMessage) {
166
166
  super(resOrMessage, HttpStatus.NOT_IMPLEMENTED);
167
167
  }
168
168
  }
@@ -171,7 +171,7 @@ exports.NotImplementedError = NotImplementedError;
171
171
  * 502 http error, Means that the server was acting as a gateway or proxy and it received an invalid answer from the upstream server.
172
172
  */
173
173
  class BadGatewayError extends base_1.MidwayHttpError {
174
- constructor(resOrMessage = 'Bad Gateway') {
174
+ constructor(resOrMessage) {
175
175
  super(resOrMessage, HttpStatus.BAD_GATEWAY);
176
176
  }
177
177
  }
@@ -180,7 +180,7 @@ exports.BadGatewayError = BadGatewayError;
180
180
  * 503 http error, Means that the server is not available now (It may be overloaded or down).
181
181
  */
182
182
  class ServiceUnavailableError extends base_1.MidwayHttpError {
183
- constructor(resOrMessage = 'Service Unavailable') {
183
+ constructor(resOrMessage) {
184
184
  super(resOrMessage, HttpStatus.SERVICE_UNAVAILABLE);
185
185
  }
186
186
  }
@@ -189,7 +189,7 @@ exports.ServiceUnavailableError = ServiceUnavailableError;
189
189
  * 504 http error, Means that the server was acting as a gateway or proxy and it didn't get answer on time from the upstream server.
190
190
  */
191
191
  class GatewayTimeoutError extends base_1.MidwayHttpError {
192
- constructor(resOrMessage = 'Gateway Timeout') {
192
+ constructor(resOrMessage) {
193
193
  super(resOrMessage, HttpStatus.GATEWAY_TIMEOUT);
194
194
  }
195
195
  }
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';
@@ -35,6 +35,7 @@ export * from './common/filterManager';
35
35
  export * from './common/applicationManager';
36
36
  export * from './setup';
37
37
  export * from './error';
38
+ export { AsyncContextManager, ASYNC_ROOT_CONTEXT, AsyncContext, } from './common/asyncContextManager';
38
39
  /**
39
40
  * proxy
40
41
  */
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.ASYNC_ROOT_CONTEXT = 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);
@@ -77,6 +81,8 @@ __exportStar(require("./common/filterManager"), exports);
77
81
  __exportStar(require("./common/applicationManager"), exports);
78
82
  __exportStar(require("./setup"), exports);
79
83
  __exportStar(require("./error"), exports);
84
+ var asyncContextManager_1 = require("./common/asyncContextManager");
85
+ Object.defineProperty(exports, "ASYNC_ROOT_CONTEXT", { enumerable: true, get: function () { return asyncContextManager_1.ASYNC_ROOT_CONTEXT; } });
80
86
  /**
81
87
  * proxy
82
88
  */
@@ -4,6 +4,7 @@ import { ILogger, LoggerOptions, LoggerContextFormat } from '@midwayjs/logger';
4
4
  import * as EventEmitter from 'events';
5
5
  import { ContextMiddlewareManager } from './common/middlewareManager';
6
6
  import _default from './config/config.default';
7
+ import { AsyncContextManager } from './common/asyncContextManager';
7
8
  export declare type PowerPartial<T> = {
8
9
  [U in keyof T]?: T[U] extends {} ? PowerPartial<T[U]> : T[U];
9
10
  };
@@ -314,10 +315,7 @@ export declare type FunctionMiddleware<CTX, R, N = unknown> = N extends true ? (
314
315
  export declare type ClassMiddleware<CTX, R, N> = new (...args: any[]) => IMiddleware<CTX, R, N>;
315
316
  export declare type CommonMiddleware<CTX, R, N> = ClassMiddleware<CTX, R, N> | FunctionMiddleware<CTX, R, N>;
316
317
  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
- }>;
318
+ export declare type MiddlewareRespond<CTX, R, N> = (context: CTX, nextOrRes?: N extends true ? R : NextFunction, next?: N) => Promise<any>;
321
319
  /**
322
320
  * Common Exception Filter definition
323
321
  */
@@ -435,6 +433,7 @@ export interface IMidwayBootstrapOptions {
435
433
  globalConfig?: Array<{
436
434
  [environmentName: string]: Record<string, any>;
437
435
  }> | Record<string, any>;
436
+ asyncContextManager?: AsyncContextManager;
438
437
  }
439
438
  export interface IConfigurationOptions {
440
439
  logger?: ILogger;
@@ -482,5 +481,7 @@ export interface MidwayAppInfo {
482
481
  export interface MidwayConfig extends FileConfigOption<typeof _default> {
483
482
  [customConfigKey: string]: unknown;
484
483
  }
484
+ export declare const ASYNC_CONTEXT_KEY: unique symbol;
485
+ export declare const ASYNC_CONTEXT_MANAGER_KEY = "MIDWAY_ASYNC_CONTEXT_MANAGER_KEY";
485
486
  export {};
486
487
  //# sourceMappingURL=interface.d.ts.map
package/dist/interface.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MIDWAY_LOGGER_WRITEABLE_DIR = exports.MidwayProcessTypeEnum = exports.REQUEST_CTX_LOGGER_CACHE_KEY = exports.HTTP_SERVER_KEY = exports.REQUEST_OBJ_CTX_KEY = exports.REQUEST_CTX_KEY = exports.ObjectLifeCycleEvent = void 0;
3
+ exports.ASYNC_CONTEXT_MANAGER_KEY = exports.ASYNC_CONTEXT_KEY = exports.MIDWAY_LOGGER_WRITEABLE_DIR = exports.MidwayProcessTypeEnum = exports.REQUEST_CTX_LOGGER_CACHE_KEY = exports.HTTP_SERVER_KEY = exports.REQUEST_OBJ_CTX_KEY = exports.REQUEST_CTX_KEY = exports.ObjectLifeCycleEvent = void 0;
4
4
  var ObjectLifeCycleEvent;
5
5
  (function (ObjectLifeCycleEvent) {
6
6
  ObjectLifeCycleEvent["BEFORE_BIND"] = "beforeBind";
@@ -19,4 +19,6 @@ var MidwayProcessTypeEnum;
19
19
  MidwayProcessTypeEnum["AGENT"] = "AGENT";
20
20
  })(MidwayProcessTypeEnum = exports.MidwayProcessTypeEnum || (exports.MidwayProcessTypeEnum = {}));
21
21
  exports.MIDWAY_LOGGER_WRITEABLE_DIR = 'MIDWAY_LOGGER_WRITEABLE_DIR';
22
+ exports.ASYNC_CONTEXT_KEY = Symbol('ASYNC_CONTEXT_KEY');
23
+ exports.ASYNC_CONTEXT_MANAGER_KEY = 'MIDWAY_ASYNC_CONTEXT_MANAGER_KEY';
22
24
  //# sourceMappingURL=interface.js.map
@@ -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
  }
@@ -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
@@ -32,6 +32,10 @@ let MidwayMiddlewareService = class MidwayMiddlewareService {
32
32
  const classMiddleware = await this.applicationContext.getAsync(fn);
33
33
  if (classMiddleware) {
34
34
  fn = await classMiddleware.resolve(app);
35
+ if (!fn) {
36
+ // for middleware enabled
37
+ continue;
38
+ }
35
39
  if (!classMiddleware.match && !classMiddleware.ignore) {
36
40
  if (!fn.name) {
37
41
  fn._name = classMiddleware.constructor.name;
@@ -88,13 +92,17 @@ let MidwayMiddlewareService = class MidwayMiddlewareService {
88
92
  return Promise.resolve(fn(context, dispatch.bind(null, i + 1), {
89
93
  index,
90
94
  })).then(result => {
91
- // need to set body
92
- if (context['body'] && !result) {
93
- result = context['body'];
94
- }
95
- else if (result && context['body'] !== result) {
95
+ /**
96
+ * 1、return ctx.body,return 的优先级更高
97
+ * 2、如果 result 有值(非 undefined),则不管什么情况,都会覆盖当前 body,注意,这里有可能赋值 null,导致 status 为 204,会在中间件处进行修正
98
+ * 3、如果 result 没值,且 ctx.body 已经赋值,则向 result 赋值
99
+ */
100
+ if (result !== undefined) {
96
101
  context['body'] = result;
97
102
  }
103
+ else if (context['body'] !== undefined) {
104
+ result = context['body'];
105
+ }
98
106
  return result;
99
107
  });
100
108
  }
@@ -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: 0,
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