@midwayjs/core 3.12.3 → 3.13.0

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,5 +1,4 @@
1
- import { CommonMiddlewareUnion, IConfigurationOptions, IMidwayApplication, IMidwayBootstrapOptions, IMidwayContainer, IMidwayContext, IMidwayFramework, CommonFilterUnion, MiddlewareRespond, CommonGuardUnion } from './interface';
2
- import { ILogger, LoggerOptions, LoggerContextFormat } from '@midwayjs/logger';
1
+ import { CommonMiddlewareUnion, IConfigurationOptions, IMidwayApplication, IMidwayBootstrapOptions, IMidwayContainer, IMidwayContext, IMidwayFramework, CommonFilterUnion, MiddlewareRespond, CommonGuardUnion, ILogger, MidwayLoggerOptions } from './interface';
3
2
  import { MidwayEnvironmentService } from './service/environmentService';
4
3
  import { MidwayConfigService } from './service/configService';
5
4
  import { MidwayInformationService } from './service/informationService';
@@ -18,7 +17,7 @@ export declare abstract class BaseFramework<APP extends IMidwayApplication<CTX>,
18
17
  protected appLogger: ILogger;
19
18
  protected defaultContext: {};
20
19
  protected contextLoggerApplyLogger: string;
21
- protected contextLoggerFormat: LoggerContextFormat;
20
+ protected contextLoggerFormat: any;
22
21
  protected middlewareManager: ContextMiddlewareManager<CTX, ResOrNext, Next>;
23
22
  protected filterManager: FilterManager<CTX, ResOrNext, Next>;
24
23
  protected guardManager: GuardManager<CTX>;
@@ -80,7 +79,7 @@ export declare abstract class BaseFramework<APP extends IMidwayApplication<CTX>,
80
79
  applyMiddleware<R, N>(lastMiddleware?: CommonMiddlewareUnion<CTX, R, N>): Promise<MiddlewareRespond<CTX, R, N>>;
81
80
  getLogger(name?: string): any;
82
81
  getCoreLogger(): ILogger;
83
- createLogger(name: string, option?: LoggerOptions): any;
82
+ createLogger(name: string, option?: MidwayLoggerOptions): any;
84
83
  getProjectName(): string;
85
84
  getFrameworkName(): string;
86
85
  useMiddleware(middleware: CommonMiddlewareUnion<CTX, ResOrNext, Next>): void;
@@ -107,7 +107,7 @@ class BaseFramework {
107
107
  return ctxLoggerCache.get(name);
108
108
  }
109
109
  // create new context logger
110
- const ctxLogger = appLogger.createContextLogger(ctx, {
110
+ const ctxLogger = this.loggerService.createContextLogger(ctx, appLogger, {
111
111
  contextFormat: this.contextLoggerFormat,
112
112
  });
113
113
  ctxLoggerCache.set(name, ctxLogger);
@@ -118,7 +118,7 @@ class BaseFramework {
118
118
  if (ctx['_logger']) {
119
119
  return ctx['_logger'];
120
120
  }
121
- ctx['_logger'] = appLogger.createContextLogger(ctx, {
121
+ ctx['_logger'] = this.loggerService.createContextLogger(ctx, appLogger, {
122
122
  contextFormat: this.contextLoggerFormat,
123
123
  });
124
124
  return ctx['_logger'];
@@ -1,8 +1,32 @@
1
- import { ILogger } from '../interface';
1
+ import { ILogger, MidwayAppInfo } from '../interface';
2
2
  export declare abstract class LoggerFactory<Logger extends ILogger, LoggerOptions> {
3
3
  abstract createLogger(name: string, options: LoggerOptions): Logger;
4
4
  abstract getLogger(loggerName: string): Logger;
5
5
  abstract close(loggerName?: string): any;
6
6
  abstract removeLogger(loggerName: string): any;
7
+ abstract getDefaultMidwayLoggerConfig(appInfo: MidwayAppInfo): {
8
+ midwayLogger: {
9
+ default?: LoggerOptions;
10
+ clients?: {
11
+ [loggerName: string]: LoggerOptions;
12
+ };
13
+ };
14
+ };
15
+ abstract createContextLogger(ctx: any, appLogger: ILogger, contextOptions?: any): ILogger;
16
+ }
17
+ export declare class DefaultConsoleLoggerFactory implements LoggerFactory<ILogger, any> {
18
+ createLogger(name: string, options: any): ILogger;
19
+ getLogger(loggerName: string): ILogger;
20
+ close(loggerName?: string): void;
21
+ removeLogger(loggerName: string): void;
22
+ getDefaultMidwayLoggerConfig(): {
23
+ midwayLogger: {
24
+ default?: any;
25
+ clients?: {
26
+ [p: string]: any;
27
+ };
28
+ };
29
+ };
30
+ createContextLogger(ctx: any, appLogger: ILogger): ILogger;
7
31
  }
8
32
  //# sourceMappingURL=loggerFactory.d.ts.map
@@ -1,7 +1,32 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LoggerFactory = void 0;
3
+ exports.DefaultConsoleLoggerFactory = exports.LoggerFactory = void 0;
4
4
  class LoggerFactory {
5
5
  }
6
6
  exports.LoggerFactory = LoggerFactory;
7
+ class DefaultConsoleLoggerFactory {
8
+ createLogger(name, options) {
9
+ return console;
10
+ }
11
+ getLogger(loggerName) {
12
+ return console;
13
+ }
14
+ close(loggerName) { }
15
+ removeLogger(loggerName) { }
16
+ getDefaultMidwayLoggerConfig() {
17
+ return {
18
+ midwayLogger: {
19
+ default: {},
20
+ clients: {
21
+ coreLogger: {},
22
+ appLogger: {},
23
+ },
24
+ },
25
+ };
26
+ }
27
+ createContextLogger(ctx, appLogger) {
28
+ return appLogger;
29
+ }
30
+ }
31
+ exports.DefaultConsoleLoggerFactory = DefaultConsoleLoggerFactory;
7
32
  //# sourceMappingURL=loggerFactory.js.map
@@ -1,30 +1,24 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const util_1 = require("../util/");
4
- const path_1 = require("path");
5
- const constants_1 = require("../constants");
6
4
  exports.default = (appInfo) => {
7
- var _a;
8
5
  const isDevelopment = (0, util_1.isDevelopmentEnvironment)((0, util_1.getCurrentEnvironment)());
9
- const logRoot = (_a = process.env[constants_1.MIDWAY_LOGGER_WRITEABLE_DIR]) !== null && _a !== void 0 ? _a : appInfo.root;
10
6
  return {
7
+ core: {
8
+ healthCheckTimeout: 1000,
9
+ },
11
10
  asyncContextManager: {
12
11
  enable: false,
13
12
  },
14
13
  midwayLogger: {
15
14
  default: {
16
- dir: (0, path_1.join)(logRoot, 'logs', appInfo.name),
17
15
  level: 'info',
18
- consoleLevel: isDevelopment ? 'info' : 'warn',
19
- auditFileDir: '.audit',
20
16
  },
21
17
  clients: {
22
18
  coreLogger: {
23
19
  level: isDevelopment ? 'info' : 'warn',
24
- fileLogName: 'midway-core.log',
25
20
  },
26
21
  appLogger: {
27
- fileLogName: 'midway-app.log',
28
22
  aliasName: 'logger',
29
23
  },
30
24
  },
@@ -20,6 +20,7 @@ export declare const FrameworkErrorEnum: {
20
20
  readonly DUPLICATE_CONTROLLER_PREFIX_OPTIONS: "MIDWAY_10016";
21
21
  readonly RETRY_OVER_MAX_TIME: "MIDWAY_10017";
22
22
  readonly INVOKE_METHOD_FORBIDDEN: "MIDWAY_10018";
23
+ readonly CODE_INVOKE_TIMEOUT: "MIDWAY_10019";
23
24
  };
24
25
  export declare class MidwayCommonError extends MidwayError {
25
26
  constructor(message: string);
@@ -78,4 +79,7 @@ export declare class MidwayRetryExceededMaxTimesError extends MidwayError {
78
79
  export declare class MidwayInvokeForbiddenError extends MidwayError {
79
80
  constructor(methodName: string, module?: any);
80
81
  }
82
+ export declare class MidwayCodeInvokeTimeoutError extends MidwayError {
83
+ constructor(methodName: string, timeout: number);
84
+ }
81
85
  //# sourceMappingURL=framework.d.ts.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MidwayInvokeForbiddenError = exports.MidwayRetryExceededMaxTimesError = 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;
3
+ exports.MidwayCodeInvokeTimeoutError = exports.MidwayInvokeForbiddenError = exports.MidwayRetryExceededMaxTimesError = 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,
@@ -22,6 +22,7 @@ exports.FrameworkErrorEnum = (0, base_1.registerErrorCode)('midway', {
22
22
  DUPLICATE_CONTROLLER_PREFIX_OPTIONS: 10016,
23
23
  RETRY_OVER_MAX_TIME: 10017,
24
24
  INVOKE_METHOD_FORBIDDEN: 10018,
25
+ CODE_INVOKE_TIMEOUT: 10019,
25
26
  });
26
27
  class MidwayCommonError extends base_1.MidwayError {
27
28
  constructor(message) {
@@ -152,4 +153,10 @@ class MidwayInvokeForbiddenError extends base_1.MidwayError {
152
153
  }
153
154
  }
154
155
  exports.MidwayInvokeForbiddenError = MidwayInvokeForbiddenError;
156
+ class MidwayCodeInvokeTimeoutError extends base_1.MidwayError {
157
+ constructor(methodName, timeout) {
158
+ super(`Invoke "${methodName}" running timeout(${timeout}ms)`, exports.FrameworkErrorEnum.CODE_INVOKE_TIMEOUT);
159
+ }
160
+ }
161
+ exports.MidwayCodeInvokeTimeoutError = MidwayCodeInvokeTimeoutError;
155
162
  //# sourceMappingURL=framework.js.map
package/dist/index.d.ts CHANGED
@@ -33,17 +33,15 @@ export { AsyncContextManager, ASYNC_ROOT_CONTEXT, AsyncContext, } from './common
33
33
  export * from './decorator';
34
34
  export * from './decorator/decoratorManager';
35
35
  export * from './decorator/constant';
36
- export { safelyGet, safeRequire, loadModule, delegateTargetPrototypeMethod, delegateTargetMethod, delegateTargetProperties, delegateTargetAllPrototypeMethod, deprecatedOutput, transformRequestObjectByType, pathMatching, wrapMiddleware, wrapAsync, isTypeScriptEnvironment, } from './util/';
36
+ export { safelyGet, safeRequire, loadModule, delegateTargetPrototypeMethod, delegateTargetMethod, delegateTargetProperties, delegateTargetAllPrototypeMethod, deprecatedOutput, transformRequestObjectByType, pathMatching, wrapMiddleware, wrapAsync, isTypeScriptEnvironment, sleep, Utils, } from './util/';
37
37
  export { extend } from './util/extend';
38
38
  export * from './util/webRouterParam';
39
39
  export * from './util/contextUtil';
40
40
  export * from './util/pathToRegexp';
41
41
  export * from './util/httpclient';
42
42
  export { retryWithAsync, retryWith } from './util/retry';
43
- export { sleep, Utils } from './util/index';
44
43
  export { Types } from './util/types';
45
44
  export { PathFileUtil } from './util/pathFileUtil';
46
45
  export { FileUtils } from './util/fs';
47
46
  export { FORMAT } from './util/format';
48
- export type { ILogger, IMidwayLogger } from '@midwayjs/logger';
49
47
  //# sourceMappingURL=index.d.ts.map
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.FORMAT = exports.FileUtils = exports.PathFileUtil = exports.Types = exports.Utils = exports.sleep = exports.retryWith = exports.retryWithAsync = exports.extend = exports.isTypeScriptEnvironment = exports.wrapAsync = exports.wrapMiddleware = exports.pathMatching = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetPrototypeMethod = exports.loadModule = exports.safeRequire = exports.safelyGet = 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.FunctionalConfiguration = exports.createConfiguration = exports.BaseFramework = exports.MidwayRequestContainer = void 0;
17
+ exports.FORMAT = exports.FileUtils = exports.PathFileUtil = exports.Types = exports.retryWith = exports.retryWithAsync = exports.extend = exports.Utils = exports.sleep = exports.isTypeScriptEnvironment = exports.wrapAsync = exports.wrapMiddleware = exports.pathMatching = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetPrototypeMethod = exports.loadModule = exports.safeRequire = exports.safelyGet = 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.FunctionalConfiguration = exports.createConfiguration = 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");
@@ -85,6 +85,8 @@ Object.defineProperty(exports, "pathMatching", { enumerable: true, get: function
85
85
  Object.defineProperty(exports, "wrapMiddleware", { enumerable: true, get: function () { return util_1.wrapMiddleware; } });
86
86
  Object.defineProperty(exports, "wrapAsync", { enumerable: true, get: function () { return util_1.wrapAsync; } });
87
87
  Object.defineProperty(exports, "isTypeScriptEnvironment", { enumerable: true, get: function () { return util_1.isTypeScriptEnvironment; } });
88
+ Object.defineProperty(exports, "sleep", { enumerable: true, get: function () { return util_1.sleep; } });
89
+ Object.defineProperty(exports, "Utils", { enumerable: true, get: function () { return util_1.Utils; } });
88
90
  var extend_1 = require("./util/extend");
89
91
  Object.defineProperty(exports, "extend", { enumerable: true, get: function () { return extend_1.extend; } });
90
92
  __exportStar(require("./util/webRouterParam"), exports);
@@ -94,9 +96,6 @@ __exportStar(require("./util/httpclient"), exports);
94
96
  var retry_1 = require("./util/retry");
95
97
  Object.defineProperty(exports, "retryWithAsync", { enumerable: true, get: function () { return retry_1.retryWithAsync; } });
96
98
  Object.defineProperty(exports, "retryWith", { enumerable: true, get: function () { return retry_1.retryWith; } });
97
- var index_1 = require("./util/index");
98
- Object.defineProperty(exports, "sleep", { enumerable: true, get: function () { return index_1.sleep; } });
99
- Object.defineProperty(exports, "Utils", { enumerable: true, get: function () { return index_1.Utils; } });
100
99
  var types_1 = require("./util/types");
101
100
  Object.defineProperty(exports, "Types", { enumerable: true, get: function () { return types_1.Types; } });
102
101
  var pathFileUtil_1 = require("./util/pathFileUtil");
@@ -1,5 +1,4 @@
1
1
  /// <reference types="node" />
2
- import type { LoggerOptions, LoggerContextFormat } from '@midwayjs/logger';
3
2
  import * as EventEmitter from 'events';
4
3
  import type { AsyncContextManager } from './common/asyncContextManager';
5
4
  import type { LoggerFactory } from './common/loggerFactory';
@@ -343,21 +342,61 @@ export interface ParamDecoratorOptions {
343
342
  throwError?: boolean;
344
343
  pipes?: PipeUnionTransform<any, any>[];
345
344
  }
345
+ /**
346
+ * Logger Options for midway, you can merge this interface in package
347
+ * @example
348
+ * ```typescript
349
+ *
350
+ * import { IMidwayLogger } from '@midwayjs/logger';
351
+ *
352
+ * declare module '@midwayjs/core/dist/interface' {
353
+ * interface ILogger extends IMidwayLogger {
354
+ * }
355
+ * }
356
+ *
357
+ * ```
358
+ */
346
359
  export interface ILogger {
347
360
  info(msg: any, ...args: any[]): void;
348
361
  debug(msg: any, ...args: any[]): void;
349
362
  error(msg: any, ...args: any[]): void;
350
363
  warn(msg: any, ...args: any[]): void;
351
364
  }
365
+ /**
366
+ * @deprecated
367
+ */
368
+ export type IMidwayLogger = ILogger;
369
+ /**
370
+ * Logger Options for midway, you can merge this interface in package
371
+ * @example
372
+ * ```typescript
373
+ *
374
+ * import { LoggerOptions } from '@midwayjs/logger';
375
+ *
376
+ * declare module '@midwayjs/core/dist/interface' {
377
+ * interface MidwayLoggerOptions extends LoggerOptions {
378
+ * logDir?: string;
379
+ * level?: string;
380
+ * }
381
+ * }
382
+ *
383
+ * ```
384
+ */
385
+ export interface MidwayLoggerOptions {
386
+ lazyLoad?: boolean;
387
+ aliasName?: string;
388
+ [key: string]: any;
389
+ }
352
390
  export interface MidwayCoreDefaultConfig {
353
- midwayLogger?: ServiceFactoryConfigOption<LoggerOptions & {
354
- lazyLoad?: boolean;
355
- }>;
391
+ midwayLogger?: ServiceFactoryConfigOption<MidwayLoggerOptions>;
356
392
  debug?: {
357
393
  recordConfigMergeOrder?: boolean;
358
394
  };
359
- asyncContextManager: {
360
- enable: boolean;
395
+ asyncContextManager?: {
396
+ enable?: boolean;
397
+ };
398
+ core?: {
399
+ healthCheckTimeout?: number;
361
400
  };
362
401
  }
363
402
  export type ServiceFactoryConfigOption<OPTIONS> = {
@@ -400,6 +439,7 @@ export interface ILifeCycle extends Partial<IObjectLifeCycle> {
400
439
  onConfigLoad?(container: IMidwayContainer, mainApp?: IMidwayApplication): Promise<any>;
401
440
  onReady?(container: IMidwayContainer, mainApp?: IMidwayApplication): Promise<void>;
402
441
  onServerReady?(container: IMidwayContainer, mainApp?: IMidwayApplication): Promise<void>;
442
+ onHealthCheck?(container: IMidwayContainer): Promise<HealthResult>;
403
443
  onStop?(container: IMidwayContainer, mainApp?: IMidwayApplication): Promise<void>;
404
444
  }
405
445
  export type ObjectContext = {
@@ -762,7 +802,7 @@ export interface IMidwayBaseApplication<CTX extends IMidwayContext> {
762
802
  * @param name
763
803
  * @param options
764
804
  */
765
- createLogger(name: string, options: LoggerOptions): ILogger;
805
+ createLogger(name: string, options: MidwayLoggerOptions): ILogger;
766
806
  /**
767
807
  * Get project name, just package.json name
768
808
  */
@@ -847,7 +887,7 @@ export interface IConfigurationOptions {
847
887
  logger?: ILogger;
848
888
  appLogger?: ILogger;
849
889
  contextLoggerApplyLogger?: string;
850
- contextLoggerFormat?: LoggerContextFormat;
890
+ contextLoggerFormat?: any;
851
891
  }
852
892
  export interface IMidwayFramework<APP extends IMidwayApplication<CTX>, CTX extends IMidwayContext, CONFIG extends IConfigurationOptions, ResOrNext = unknown, Next = unknown> {
853
893
  app: APP;
@@ -866,7 +906,7 @@ export interface IMidwayFramework<APP extends IMidwayApplication<CTX>, CTX exten
866
906
  getBaseDir(): string;
867
907
  getLogger(name?: string): ILogger;
868
908
  getCoreLogger(): ILogger;
869
- createLogger(name: string, options: LoggerOptions): ILogger;
909
+ createLogger(name: string, options: MidwayLoggerOptions): ILogger;
870
910
  getProjectName(): string;
871
911
  useMiddleware(Middleware: CommonMiddlewareUnion<CTX, ResOrNext, Next>): void;
872
912
  getMiddleware(): IMiddlewareManager<CTX, ResOrNext, Next>;
@@ -909,5 +949,34 @@ export interface ISimulation {
909
949
  appTearDown?(app: IMidwayApplication): Promise<void>;
910
950
  enableCondition(): boolean | Promise<boolean>;
911
951
  }
952
+ export interface HealthResult {
953
+ /**
954
+ * health status
955
+ */
956
+ status: boolean;
957
+ /**
958
+ * failed reason
959
+ */
960
+ reason?: string;
961
+ }
962
+ export interface HealthResults {
963
+ /**
964
+ * health status
965
+ */
966
+ status: boolean;
967
+ /**
968
+ * first failed namespace
969
+ */
970
+ namespace: string;
971
+ /**
972
+ * first failed reason
973
+ */
974
+ reason?: string;
975
+ results?: Array<{
976
+ namespace: string;
977
+ status: boolean;
978
+ reason?: string;
979
+ }>;
980
+ }
912
981
  export {};
913
982
  //# sourceMappingURL=interface.d.ts.map
@@ -34,6 +34,7 @@ export declare class MidwayConfigService implements IConfigService {
34
34
  */
35
35
  addFilter(filter: (config: Record<string, any>) => Record<string, any>): void;
36
36
  protected runWithFilter(config: Record<string, any>): Record<string, any>;
37
+ getAppInfo(): MidwayAppInfo;
37
38
  }
38
39
  export {};
39
40
  //# sourceMappingURL=configService.d.ts.map
@@ -224,6 +224,9 @@ let MidwayConfigService = class MidwayConfigService {
224
224
  }
225
225
  return config;
226
226
  }
227
+ getAppInfo() {
228
+ return this.appInfo;
229
+ }
227
230
  };
228
231
  __decorate([
229
232
  (0, decorator_1.Inject)(),
@@ -131,6 +131,7 @@ let MidwayFrameworkService = class MidwayFrameworkService {
131
131
  }
132
132
  global['MIDWAY_MAIN_FRAMEWORK'] = this.mainFramework =
133
133
  (_b = this.applicationManager.getFramework(mainNs)) !== null && _b !== void 0 ? _b : this.globalFrameworkList[0];
134
+ debug(`[core]: Current main Framework is "${mainNs}".`);
134
135
  }
135
136
  // init aspect module
136
137
  await this.aspectService.loadAspect();
@@ -146,6 +147,12 @@ let MidwayFrameworkService = class MidwayFrameworkService {
146
147
  return this.applicationManager.getFramework(namespaceOrFrameworkType);
147
148
  }
148
149
  async runFramework() {
150
+ const namespaceList = this.applicationContext.getNamespaceList();
151
+ // globalFrameworkList 需要基于 namespaceList 进行排序,不然会出现顺序问题
152
+ this.globalFrameworkList = this.globalFrameworkList.sort((a, b) => {
153
+ return (namespaceList.indexOf(a.getNamespace()) -
154
+ namespaceList.indexOf(b.getNamespace()));
155
+ });
149
156
  for (const frameworkInstance of this.globalFrameworkList) {
150
157
  // if enable, just init framework
151
158
  if (frameworkInstance.isEnable()) {
@@ -0,0 +1,14 @@
1
+ import { HealthResults, IMidwayContainer } from '../interface';
2
+ import { MidwayConfigService } from './configService';
3
+ import { MidwayLifeCycleService } from './lifeCycleService';
4
+ export declare class MidwayHealthService {
5
+ protected configService: MidwayConfigService;
6
+ protected lifeCycleService: MidwayLifeCycleService;
7
+ protected applicationContext: IMidwayContainer;
8
+ private healthCheckTimeout;
9
+ private healthCheckMethods;
10
+ protected init(): Promise<void>;
11
+ getStatus(): Promise<HealthResults>;
12
+ setCheckTimeout(timeout: number): void;
13
+ }
14
+ //# sourceMappingURL=healthService.d.ts.map
@@ -0,0 +1,106 @@
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.MidwayHealthService = void 0;
13
+ const decorator_1 = require("../decorator");
14
+ const interface_1 = require("../interface");
15
+ const configService_1 = require("./configService");
16
+ const lifeCycleService_1 = require("./lifeCycleService");
17
+ const util_1 = require("../util");
18
+ let MidwayHealthService = class MidwayHealthService {
19
+ constructor() {
20
+ this.healthCheckTimeout = 1000;
21
+ this.healthCheckMethods = [];
22
+ }
23
+ async init() {
24
+ const healthCheckTimeout = this.configService.getConfiguration('core.healthCheckTimeout') || 1000;
25
+ this.setCheckTimeout(healthCheckTimeout);
26
+ for (const lifecycleInstance of this.lifeCycleService.getLifecycleInstanceList()) {
27
+ if (lifecycleInstance.instance &&
28
+ lifecycleInstance.instance['onHealthCheck']) {
29
+ this.healthCheckMethods.push({
30
+ item: lifecycleInstance.instance['onHealthCheck'],
31
+ meta: {
32
+ namespace: lifecycleInstance.namespace,
33
+ },
34
+ });
35
+ }
36
+ }
37
+ }
38
+ async getStatus() {
39
+ const checkResult = await (0, util_1.createPromiseTimeoutInvokeChain)({
40
+ promiseItems: this.healthCheckMethods.map(item => {
41
+ return {
42
+ item: item.item(this.applicationContext),
43
+ meta: item.meta,
44
+ };
45
+ }),
46
+ timeout: this.healthCheckTimeout,
47
+ methodName: 'configuration.onHealthCheck',
48
+ onSuccess: (result, meta) => {
49
+ if (result['status'] !== undefined) {
50
+ return {
51
+ namespace: meta.namespace,
52
+ ...result,
53
+ };
54
+ }
55
+ else {
56
+ return {
57
+ status: false,
58
+ namespace: meta.namespace,
59
+ reason: 'configuration.onHealthCheck return value must be object and contain status field',
60
+ };
61
+ }
62
+ },
63
+ onFail: (err, meta) => {
64
+ return {
65
+ status: false,
66
+ namespace: meta.namespace,
67
+ reason: err.message,
68
+ };
69
+ },
70
+ });
71
+ const failedResult = checkResult.find(item => !item.status);
72
+ return {
73
+ status: !failedResult,
74
+ namespace: failedResult === null || failedResult === void 0 ? void 0 : failedResult.namespace,
75
+ reason: failedResult === null || failedResult === void 0 ? void 0 : failedResult.reason,
76
+ results: checkResult,
77
+ };
78
+ }
79
+ setCheckTimeout(timeout) {
80
+ this.healthCheckTimeout = timeout;
81
+ }
82
+ };
83
+ __decorate([
84
+ (0, decorator_1.Inject)(),
85
+ __metadata("design:type", configService_1.MidwayConfigService)
86
+ ], MidwayHealthService.prototype, "configService", void 0);
87
+ __decorate([
88
+ (0, decorator_1.Inject)(),
89
+ __metadata("design:type", lifeCycleService_1.MidwayLifeCycleService)
90
+ ], MidwayHealthService.prototype, "lifeCycleService", void 0);
91
+ __decorate([
92
+ (0, decorator_1.ApplicationContext)(),
93
+ __metadata("design:type", Object)
94
+ ], MidwayHealthService.prototype, "applicationContext", void 0);
95
+ __decorate([
96
+ (0, decorator_1.Init)(),
97
+ __metadata("design:type", Function),
98
+ __metadata("design:paramtypes", []),
99
+ __metadata("design:returntype", Promise)
100
+ ], MidwayHealthService.prototype, "init", null);
101
+ MidwayHealthService = __decorate([
102
+ (0, decorator_1.Provide)(),
103
+ (0, decorator_1.Scope)(interface_1.ScopeEnum.Singleton)
104
+ ], MidwayHealthService);
105
+ exports.MidwayHealthService = MidwayHealthService;
106
+ //# sourceMappingURL=healthService.js.map
@@ -7,10 +7,27 @@ export declare class MidwayLifeCycleService {
7
7
  protected frameworkService: MidwayFrameworkService;
8
8
  protected configService: MidwayConfigService;
9
9
  protected mockService: MidwayMockService;
10
+ private lifecycleInstanceList;
10
11
  constructor(applicationContext: IMidwayContainer);
11
12
  protected init(): Promise<void>;
12
13
  stop(): Promise<void>;
14
+ /**
15
+ * run some lifecycle in configuration
16
+ * @param lifecycleInstanceOrList
17
+ * @param lifecycle
18
+ * @param resultHandler
19
+ */
13
20
  private runContainerLifeCycle;
21
+ /**
22
+ * run object lifecycle
23
+ * @param lifecycleInstanceList
24
+ * @param lifecycle
25
+ */
14
26
  private runObjectLifeCycle;
27
+ getLifecycleInstanceList(): {
28
+ target: any;
29
+ namespace: string;
30
+ instance?: any;
31
+ }[];
15
32
  }
16
33
  //# sourceMappingURL=lifeCycleService.d.ts.map
@@ -21,6 +21,7 @@ const debug = (0, util_1.debuglog)('midway:debug');
21
21
  let MidwayLifeCycleService = class MidwayLifeCycleService {
22
22
  constructor(applicationContext) {
23
23
  this.applicationContext = applicationContext;
24
+ this.lifecycleInstanceList = [];
24
25
  }
25
26
  async init() {
26
27
  // exec simulator init
@@ -28,7 +29,6 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
28
29
  // run lifecycle
29
30
  const cycles = (0, decorator_1.listModule)(decorator_1.CONFIGURATION_KEY);
30
31
  debug(`[core]: Found Configuration length = ${cycles.length}`);
31
- const lifecycleInstanceList = [];
32
32
  for (const cycle of cycles) {
33
33
  if (cycle.target instanceof configuration_1.FunctionalConfiguration) {
34
34
  // 函数式写法
@@ -39,30 +39,30 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
39
39
  debug(`[core]: Lifecycle run ${cycle.namespace} init`);
40
40
  cycle.instance = await this.applicationContext.getAsync(cycle.target);
41
41
  }
42
- cycle.instance && lifecycleInstanceList.push(cycle);
42
+ cycle.instance && this.lifecycleInstanceList.push(cycle);
43
43
  }
44
44
  // bind object lifecycle
45
45
  await Promise.all([
46
- this.runObjectLifeCycle(lifecycleInstanceList, 'onBeforeObjectCreated'),
47
- this.runObjectLifeCycle(lifecycleInstanceList, 'onObjectCreated'),
48
- this.runObjectLifeCycle(lifecycleInstanceList, 'onObjectInit'),
49
- this.runObjectLifeCycle(lifecycleInstanceList, 'onBeforeObjectDestroy'),
46
+ this.runObjectLifeCycle(this.lifecycleInstanceList, 'onBeforeObjectCreated'),
47
+ this.runObjectLifeCycle(this.lifecycleInstanceList, 'onObjectCreated'),
48
+ this.runObjectLifeCycle(this.lifecycleInstanceList, 'onObjectInit'),
49
+ this.runObjectLifeCycle(this.lifecycleInstanceList, 'onBeforeObjectDestroy'),
50
50
  ]);
51
51
  // bind framework lifecycle
52
52
  // onAppError
53
53
  // exec onConfigLoad()
54
- await this.runContainerLifeCycle(lifecycleInstanceList, 'onConfigLoad', configData => {
54
+ await this.runContainerLifeCycle(this.lifecycleInstanceList, 'onConfigLoad', configData => {
55
55
  if (configData) {
56
56
  this.configService.addObject(configData);
57
57
  }
58
58
  });
59
59
  await this.mockService.runSimulatorSetup();
60
60
  // exec onReady()
61
- await this.runContainerLifeCycle(lifecycleInstanceList, 'onReady');
61
+ await this.runContainerLifeCycle(this.lifecycleInstanceList, 'onReady');
62
62
  // exec framework.run()
63
63
  await this.frameworkService.runFramework();
64
64
  // exec onServerReady()
65
- await this.runContainerLifeCycle(lifecycleInstanceList, 'onServerReady');
65
+ await this.runContainerLifeCycle(this.lifecycleInstanceList, 'onServerReady');
66
66
  // clear config merge cache
67
67
  if (!this.configService.getConfiguration('debug.recordConfigMergeOrder')) {
68
68
  this.configService.clearConfigMergeOrder();
@@ -86,6 +86,12 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
86
86
  // stop framework
87
87
  await this.frameworkService.stopFramework();
88
88
  }
89
+ /**
90
+ * run some lifecycle in configuration
91
+ * @param lifecycleInstanceOrList
92
+ * @param lifecycle
93
+ * @param resultHandler
94
+ */
89
95
  async runContainerLifeCycle(lifecycleInstanceOrList, lifecycle, resultHandler) {
90
96
  if (Array.isArray(lifecycleInstanceOrList)) {
91
97
  for (const cycle of lifecycleInstanceOrList) {
@@ -108,6 +114,11 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
108
114
  }
109
115
  }
110
116
  }
117
+ /**
118
+ * run object lifecycle
119
+ * @param lifecycleInstanceList
120
+ * @param lifecycle
121
+ */
111
122
  async runObjectLifeCycle(lifecycleInstanceList, lifecycle) {
112
123
  for (const cycle of lifecycleInstanceList) {
113
124
  if (typeof cycle.instance[lifecycle] === 'function') {
@@ -116,6 +127,9 @@ let MidwayLifeCycleService = class MidwayLifeCycleService {
116
127
  }
117
128
  }
118
129
  }
130
+ getLifecycleInstanceList() {
131
+ return this.lifecycleInstanceList;
132
+ }
119
133
  };
120
134
  __decorate([
121
135
  (0, decorator_1.Inject)(),
@@ -1,6 +1,6 @@
1
1
  import { MidwayConfigService } from './configService';
2
2
  import { ServiceFactory } from '../common/serviceFactory';
3
- import { ILogger, IMidwayContainer } from '../interface';
3
+ import { ILogger, IMidwayContainer, IMidwayContext, MidwayLoggerOptions } from '../interface';
4
4
  import { LoggerFactory } from '../common/loggerFactory';
5
5
  export declare class MidwayLoggerService extends ServiceFactory<ILogger> {
6
6
  readonly applicationContext: IMidwayContainer;
@@ -8,12 +8,14 @@ export declare class MidwayLoggerService extends ServiceFactory<ILogger> {
8
8
  configService: MidwayConfigService;
9
9
  private loggerFactory;
10
10
  private lazyLoggerConfigMap;
11
+ private aliasLoggerMap;
11
12
  constructor(applicationContext: IMidwayContainer, globalOptions?: {});
12
13
  protected init(): void;
13
14
  protected createClient(config: any, name?: string): void;
14
15
  getName(): string;
15
- createLogger(name: any, config: any): any;
16
+ createLogger(name: string, config: MidwayLoggerOptions): any;
16
17
  getLogger(name: string): any;
17
18
  getCurrentLoggerFactory(): LoggerFactory<any, any>;
19
+ createContextLogger(ctx: IMidwayContext, appLogger: ILogger, contextOptions?: any): ILogger;
18
20
  }
19
21
  //# sourceMappingURL=loggerService.d.ts.map
@@ -14,22 +14,41 @@ const decorator_1 = require("../decorator");
14
14
  const configService_1 = require("./configService");
15
15
  const serviceFactory_1 = require("../common/serviceFactory");
16
16
  const interface_1 = require("../interface");
17
- const logger_1 = require("@midwayjs/logger");
17
+ const loggerFactory_1 = require("../common/loggerFactory");
18
+ const error_1 = require("../error");
18
19
  let MidwayLoggerService = class MidwayLoggerService extends serviceFactory_1.ServiceFactory {
19
20
  constructor(applicationContext, globalOptions = {}) {
20
21
  super();
21
22
  this.applicationContext = applicationContext;
22
23
  this.globalOptions = globalOptions;
23
24
  this.lazyLoggerConfigMap = new Map();
25
+ this.aliasLoggerMap = new Map();
24
26
  }
25
27
  init() {
26
28
  var _a;
27
- this.loggerFactory = this.globalOptions['loggerFactory'] || logger_1.loggers;
29
+ const loggerFactory = this.configService.getConfiguration('loggerFactory');
30
+ // load logger factory from user config first
31
+ this.loggerFactory =
32
+ loggerFactory ||
33
+ this.globalOptions['loggerFactory'] ||
34
+ new loggerFactory_1.DefaultConsoleLoggerFactory();
35
+ // check
36
+ if (!this.loggerFactory.getDefaultMidwayLoggerConfig) {
37
+ throw new error_1.MidwayFeatureNoLongerSupportedError('please upgrade your @midwayjs/logger to latest version');
38
+ }
39
+ const defaultLoggerConfig = this.loggerFactory.getDefaultMidwayLoggerConfig(this.configService.getAppInfo());
40
+ // merge to user config
41
+ this.configService.addObject(defaultLoggerConfig, true);
42
+ // init logger
28
43
  this.initClients(this.configService.getConfiguration('midwayLogger'));
29
44
  // alias inject logger
30
45
  (_a = this.applicationContext) === null || _a === void 0 ? void 0 : _a.registerObject('logger', this.getLogger('appLogger'));
31
46
  }
32
47
  createClient(config, name) {
48
+ if (config.aliasName) {
49
+ // mapping alias logger name to real logger name
50
+ this.aliasLoggerMap.set(config.aliasName, name);
51
+ }
33
52
  if (!config.lazyLoad) {
34
53
  this.loggerFactory.createLogger(name, config);
35
54
  }
@@ -42,9 +61,14 @@ let MidwayLoggerService = class MidwayLoggerService extends serviceFactory_1.Ser
42
61
  return 'logger';
43
62
  }
44
63
  createLogger(name, config) {
64
+ delete config['aliasName'];
45
65
  return this.loggerFactory.createLogger(name, config);
46
66
  }
47
67
  getLogger(name) {
68
+ if (this.aliasLoggerMap.has(name)) {
69
+ // get real logger name
70
+ name = this.aliasLoggerMap.get(name);
71
+ }
48
72
  const logger = this.loggerFactory.getLogger(name);
49
73
  if (logger) {
50
74
  return logger;
@@ -59,6 +83,9 @@ let MidwayLoggerService = class MidwayLoggerService extends serviceFactory_1.Ser
59
83
  getCurrentLoggerFactory() {
60
84
  return this.loggerFactory;
61
85
  }
86
+ createContextLogger(ctx, appLogger, contextOptions) {
87
+ return this.loggerFactory.createContextLogger(ctx, appLogger, contextOptions);
88
+ }
62
89
  };
63
90
  __decorate([
64
91
  (0, decorator_1.Inject)(),
package/dist/setup.js CHANGED
@@ -7,6 +7,7 @@ const decorator_1 = require("./decorator");
7
7
  const util = require("util");
8
8
  const slsFunctionService_1 = require("./service/slsFunctionService");
9
9
  const path_1 = require("path");
10
+ const healthService_1 = require("./service/healthService");
10
11
  const debug = util.debuglog('midway:debug');
11
12
  let stepIdx = 1;
12
13
  function printStepDebugInfo(stepInfo) {
@@ -134,6 +135,7 @@ async function prepareGlobalApplicationContextAsync(globalOptions) {
134
135
  applicationContext.bindClass(_1.MidwayMockService);
135
136
  applicationContext.bindClass(_1.MidwayWebRouterService);
136
137
  applicationContext.bindClass(slsFunctionService_1.MidwayServerlessFunctionService);
138
+ applicationContext.bindClass(healthService_1.MidwayHealthService);
137
139
  printStepDebugInfo('Binding preload module');
138
140
  // bind preload module
139
141
  if (globalOptions.preloadModules && globalOptions.preloadModules.length) {
@@ -227,6 +229,7 @@ function prepareGlobalApplicationContext(globalOptions) {
227
229
  applicationContext.bindClass(_1.MidwayMockService);
228
230
  applicationContext.bindClass(_1.MidwayWebRouterService);
229
231
  applicationContext.bindClass(slsFunctionService_1.MidwayServerlessFunctionService);
232
+ applicationContext.bindClass(healthService_1.MidwayHealthService);
230
233
  printStepDebugInfo('Binding preload module');
231
234
  // bind preload module
232
235
  if (globalOptions.preloadModules && globalOptions.preloadModules.length) {
@@ -123,6 +123,22 @@ export declare function generateRandomId(): string;
123
123
  export declare function merge(target: any, src: any): any;
124
124
  export declare function toAsyncFunction<T extends (...args: any[]) => any>(method: T): (...args: Parameters<T>) => Promise<ReturnType<T>>;
125
125
  export declare function isTypeScriptEnvironment(): boolean;
126
+ /**
127
+ * Create a Promise that resolves after the specified time
128
+ * @param options
129
+ */
130
+ export declare function createPromiseTimeoutInvokeChain<Result>(options: {
131
+ promiseItems: Array<Promise<any> | {
132
+ item: Promise<any>;
133
+ meta?: any;
134
+ timeout?: number;
135
+ }>;
136
+ timeout: number;
137
+ methodName: string;
138
+ onSuccess?: (result: any, meta: any) => Result | Promise<Result>;
139
+ onFail: (err: Error, meta: any) => Result | Promise<Result>;
140
+ isConcurrent?: boolean;
141
+ }): Promise<Result[]>;
126
142
  export declare const Utils: {
127
143
  sleep: typeof sleep;
128
144
  getParamNames: typeof getParamNames;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Utils = exports.isTypeScriptEnvironment = exports.toAsyncFunction = exports.merge = exports.generateRandomId = exports.getParamNames = exports.sleep = exports.wrapAsync = exports.isIncludeProperty = exports.wrapMiddleware = exports.pathMatching = exports.toPathMatch = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.getCurrentDateString = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetPrototypeMethod = exports.joinURLPath = exports.getUserHome = exports.parsePrefix = exports.safelyGet = exports.loadModule = exports.safeRequire = exports.getCurrentEnvironment = exports.isDevelopmentEnvironment = void 0;
3
+ exports.Utils = exports.createPromiseTimeoutInvokeChain = exports.isTypeScriptEnvironment = exports.toAsyncFunction = exports.merge = exports.generateRandomId = exports.getParamNames = exports.sleep = exports.wrapAsync = exports.isIncludeProperty = exports.wrapMiddleware = exports.pathMatching = exports.toPathMatch = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.getCurrentDateString = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetPrototypeMethod = exports.joinURLPath = exports.getUserHome = exports.parsePrefix = exports.safelyGet = exports.loadModule = exports.safeRequire = exports.getCurrentEnvironment = exports.isDevelopmentEnvironment = void 0;
4
4
  const path_1 = require("path");
5
5
  const fs_1 = require("fs");
6
6
  const util_1 = require("util");
@@ -496,6 +496,79 @@ function isTypeScriptEnvironment() {
496
496
  return TS_MODE_PROCESS_FLAG === 'true' || !!require.extensions['.ts'];
497
497
  }
498
498
  exports.isTypeScriptEnvironment = isTypeScriptEnvironment;
499
+ /**
500
+ * Create a Promise that resolves after the specified time
501
+ * @param options
502
+ */
503
+ async function createPromiseTimeoutInvokeChain(options) {
504
+ var _a;
505
+ if (!options.onSuccess) {
506
+ options.onSuccess = async (result) => {
507
+ return result;
508
+ };
509
+ }
510
+ options.isConcurrent = (_a = options.isConcurrent) !== null && _a !== void 0 ? _a : true;
511
+ options.promiseItems = options.promiseItems.map(item => {
512
+ if (item instanceof Promise) {
513
+ return { item };
514
+ }
515
+ else {
516
+ return item;
517
+ }
518
+ });
519
+ // filter promise
520
+ options.promiseItems = options.promiseItems.filter(item => {
521
+ return item['item'] instanceof Promise;
522
+ });
523
+ if (options.isConcurrent) {
524
+ // For each check item, we create a timeout Promise
525
+ const checkPromises = options.promiseItems.map(item => {
526
+ const timeoutPromise = new Promise((_, reject) => {
527
+ var _a;
528
+ // The timeout Promise fails after the specified time
529
+ setTimeout(() => {
530
+ var _a;
531
+ return reject(new error_1.MidwayCodeInvokeTimeoutError(options.methodName, (_a = item['timeout']) !== null && _a !== void 0 ? _a : options.timeout));
532
+ }, (_a = item['timeout']) !== null && _a !== void 0 ? _a : options.timeout);
533
+ });
534
+ // We use Promise.race to wait for either the check item or the timeout Promise
535
+ return (Promise.race([item['item'], timeoutPromise])
536
+ // If the check item Promise resolves, we set the result to success
537
+ .then(re => {
538
+ return options.onSuccess(re, item['meta']);
539
+ })
540
+ // If the timeout Promise resolves (i.e., the check item Promise did not resolve in time), we set the result to failure
541
+ .catch(err => {
542
+ return options.onFail(err, item['meta']);
543
+ }));
544
+ });
545
+ return Promise.all(checkPromises);
546
+ }
547
+ else {
548
+ const results = [];
549
+ for (const item of options.promiseItems) {
550
+ const timeoutPromise = new Promise((_, reject) => {
551
+ var _a;
552
+ setTimeout(() => {
553
+ var _a;
554
+ return reject(new error_1.MidwayCodeInvokeTimeoutError(options.methodName, (_a = item['timeout']) !== null && _a !== void 0 ? _a : options.timeout));
555
+ }, (_a = item['timeout']) !== null && _a !== void 0 ? _a : options.timeout);
556
+ });
557
+ try {
558
+ const result = await Promise.race([item['item'], timeoutPromise]).then(re => {
559
+ return options.onSuccess(re, item['meta']);
560
+ });
561
+ results.push(result);
562
+ }
563
+ catch (error) {
564
+ results.push(options.onFail(error, item['meta']));
565
+ break;
566
+ }
567
+ }
568
+ return results;
569
+ }
570
+ }
571
+ exports.createPromiseTimeoutInvokeChain = createPromiseTimeoutInvokeChain;
499
572
  exports.Utils = {
500
573
  sleep,
501
574
  getParamNames,
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@midwayjs/core",
3
- "version": "3.12.3",
3
+ "version": "3.13.0",
4
4
  "description": "midway core",
5
- "main": "dist/index",
5
+ "main": "dist/index.js",
6
6
  "typings": "dist/index.d.ts",
7
7
  "scripts": {
8
8
  "build": "tsc",
@@ -22,14 +22,14 @@
22
22
  ],
23
23
  "license": "MIT",
24
24
  "devDependencies": {
25
- "koa": "2.14.1",
25
+ "@midwayjs/logger": "^3.0.0",
26
+ "koa": "2.14.2",
26
27
  "mm": "3.3.0",
27
28
  "raw-body": "2.5.2",
28
29
  "sinon": "15.2.0"
29
30
  },
30
31
  "dependencies": {
31
32
  "@midwayjs/glob": "^1.0.2",
32
- "@midwayjs/logger": "^2.15.0",
33
33
  "class-transformer": "0.5.1",
34
34
  "picomatch": "2.3.1",
35
35
  "reflect-metadata": "0.1.13"
@@ -42,5 +42,5 @@
42
42
  "engines": {
43
43
  "node": ">=12"
44
44
  },
45
- "gitHead": "0b6638726c4722d5a6ee8075fea0a0b68378452c"
45
+ "gitHead": "9f55734afa5b08dcf46bc89493ec8edaa8c6202b"
46
46
  }