@midwayjs/core 3.1.6 → 3.2.2

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.
@@ -7,6 +7,7 @@ import { MidwayLoggerService } from './service/loggerService';
7
7
  import { ContextMiddlewareManager } from './common/middlewareManager';
8
8
  import { MidwayMiddlewareService } from './service/middlewareService';
9
9
  import { FilterManager } from './common/filterManager';
10
+ import { MidwayMockService } from './service/mockService';
10
11
  export declare abstract class BaseFramework<APP extends IMidwayApplication<CTX>, CTX extends IMidwayContext, OPT extends IConfigurationOptions, ResOrNext = unknown, Next = unknown> implements IMidwayFramework<APP, CTX, OPT, ResOrNext, Next> {
11
12
  readonly applicationContext: IMidwayContainer;
12
13
  app: APP;
@@ -24,6 +25,7 @@ export declare abstract class BaseFramework<APP extends IMidwayApplication<CTX>,
24
25
  configService: MidwayConfigService;
25
26
  informationService: MidwayInformationService;
26
27
  middlewareService: MidwayMiddlewareService<CTX, ResOrNext, Next>;
28
+ mockService: MidwayMockService;
27
29
  constructor(applicationContext: IMidwayContainer);
28
30
  init(): Promise<this>;
29
31
  abstract configure(options?: OPT): any;
@@ -20,6 +20,7 @@ const loggerService_1 = require("./service/loggerService");
20
20
  const middlewareManager_1 = require("./common/middlewareManager");
21
21
  const middlewareService_1 = require("./service/middlewareService");
22
22
  const filterManager_1 = require("./common/filterManager");
23
+ const mockService_1 = require("./service/mockService");
23
24
  const util = require("util");
24
25
  const debug = util.debuglog('midway:debug');
25
26
  class BaseFramework {
@@ -232,6 +233,7 @@ class BaseFramework {
232
233
  async applyMiddleware(lastMiddleware) {
233
234
  if (!this.composeMiddleware) {
234
235
  this.middlewareManager.insertFirst((async (ctx, next) => {
236
+ this.mockService.applyContextMocks(this.app, ctx);
235
237
  let returnResult = undefined;
236
238
  try {
237
239
  const result = await next();
@@ -308,6 +310,10 @@ __decorate([
308
310
  (0, decorator_1.Inject)(),
309
311
  __metadata("design:type", middlewareService_1.MidwayMiddlewareService)
310
312
  ], BaseFramework.prototype, "middlewareService", void 0);
313
+ __decorate([
314
+ (0, decorator_1.Inject)(),
315
+ __metadata("design:type", mockService_1.MidwayMockService)
316
+ ], BaseFramework.prototype, "mockService", void 0);
311
317
  __decorate([
312
318
  (0, decorator_1.Init)(),
313
319
  __metadata("design:type", Function),
@@ -32,7 +32,12 @@ class RefResolver {
32
32
  const mr = managed;
33
33
  if (mr.injectMode === decorator_1.InjectModeEnum.Class &&
34
34
  !((_a = this.factory.context.parent) !== null && _a !== void 0 ? _a : this.factory.context).hasDefinition(mr.name)) {
35
- throw new error_1.MidwayMissingImportComponentError(originName);
35
+ if (originName === 'loggerService') {
36
+ throw new error_1.MidwayInconsistentVersionError();
37
+ }
38
+ else {
39
+ throw new error_1.MidwayMissingImportComponentError(originName);
40
+ }
36
41
  }
37
42
  return this.factory.context.get(mr.name, mr.args, {
38
43
  originName,
@@ -43,7 +48,12 @@ class RefResolver {
43
48
  const mr = managed;
44
49
  if (mr.injectMode === decorator_1.InjectModeEnum.Class &&
45
50
  !((_a = this.factory.context.parent) !== null && _a !== void 0 ? _a : this.factory.context).hasDefinition(mr.name)) {
46
- throw new error_1.MidwayMissingImportComponentError(originName);
51
+ if (originName === 'loggerService') {
52
+ throw new error_1.MidwayInconsistentVersionError();
53
+ }
54
+ else {
55
+ throw new error_1.MidwayMissingImportComponentError(originName);
56
+ }
47
57
  }
48
58
  return this.factory.context.getAsync(mr.name, mr.args, {
49
59
  originName,
@@ -14,6 +14,7 @@ export declare const FrameworkErrorEnum: {
14
14
  readonly SINGLETON_INJECT_REQUEST: "MIDWAY_10010";
15
15
  readonly MISSING_IMPORTS: "MIDWAY_10011";
16
16
  readonly UTIL_HTTP_TIMEOUT: "MIDWAY_10012";
17
+ readonly INCONSISTENT_VERSION: "MIDWAY_10013";
17
18
  };
18
19
  export declare class MidwayCommonError extends MidwayError {
19
20
  constructor(message: string);
@@ -54,4 +55,7 @@ export declare class MidwayMissingImportComponentError extends MidwayError {
54
55
  export declare class MidwayUtilHttpClientTimeoutError extends MidwayError {
55
56
  constructor(message: string);
56
57
  }
58
+ export declare class MidwayInconsistentVersionError extends MidwayError {
59
+ constructor();
60
+ }
57
61
  //# sourceMappingURL=framework.d.ts.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MidwayUtilHttpClientTimeoutError = exports.MidwayMissingImportComponentError = exports.MidwaySingletonInjectRequestError = exports.MidwayUseWrongMethodError = exports.MidwayDuplicateRouteError = exports.MidwayResolverMissingError = exports.MidwayConfigMissingError = exports.MidwayFeatureNotImplementedError = exports.MidwayFeatureNoLongerSupportedError = exports.MidwayDefinitionNotFoundError = exports.MidwayParameterError = exports.MidwayCommonError = exports.FrameworkErrorEnum = void 0;
3
+ exports.MidwayInconsistentVersionError = exports.MidwayUtilHttpClientTimeoutError = exports.MidwayMissingImportComponentError = exports.MidwaySingletonInjectRequestError = exports.MidwayUseWrongMethodError = exports.MidwayDuplicateRouteError = exports.MidwayResolverMissingError = 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,
@@ -16,6 +16,7 @@ exports.FrameworkErrorEnum = (0, base_1.registerErrorCode)('midway', {
16
16
  SINGLETON_INJECT_REQUEST: 10010,
17
17
  MISSING_IMPORTS: 10011,
18
18
  UTIL_HTTP_TIMEOUT: 10012,
19
+ INCONSISTENT_VERSION: 10013,
19
20
  });
20
21
  class MidwayCommonError extends base_1.MidwayError {
21
22
  constructor(message) {
@@ -107,4 +108,11 @@ class MidwayUtilHttpClientTimeoutError extends base_1.MidwayError {
107
108
  }
108
109
  }
109
110
  exports.MidwayUtilHttpClientTimeoutError = MidwayUtilHttpClientTimeoutError;
111
+ class MidwayInconsistentVersionError extends base_1.MidwayError {
112
+ constructor() {
113
+ const text = 'We find a latest dependency package installed, please remove the lock file and use "npm update" to upgrade all dependencies first.';
114
+ super(text, exports.FrameworkErrorEnum.INCONSISTENT_VERSION);
115
+ }
116
+ }
117
+ exports.MidwayInconsistentVersionError = MidwayInconsistentVersionError;
110
118
  //# sourceMappingURL=framework.js.map
package/dist/index.d.ts CHANGED
@@ -20,6 +20,7 @@ export { MidwayAspectService } from './service/aspectService';
20
20
  export { MidwayLifeCycleService } from './service/lifeCycleService';
21
21
  export { MidwayMiddlewareService } from './service/middlewareService';
22
22
  export { MidwayDecoratorService } from './service/decoratorService';
23
+ export { MidwayMockService } from './service/mockService';
23
24
  export * from './service/pipelineService';
24
25
  export * from './util/contextUtil';
25
26
  export * from './common/serviceFactory';
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.MidwayDecoratorService = exports.MidwayMiddlewareService = exports.MidwayLifeCycleService = exports.MidwayAspectService = exports.MidwayFrameworkService = exports.MidwayLoggerService = exports.MidwayInformationService = exports.MidwayEnvironmentService = exports.MidwayConfigService = exports.createConfiguration = exports.extend = exports.wrapMiddleware = exports.pathMatching = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetPrototypeMethod = exports.safeRequire = exports.safelyGet = exports.BaseFramework = exports.MidwayRequestContainer = void 0;
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.wrapMiddleware = exports.pathMatching = exports.transformRequestObjectByType = exports.deprecatedOutput = 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");
@@ -59,6 +59,8 @@ var middlewareService_1 = require("./service/middlewareService");
59
59
  Object.defineProperty(exports, "MidwayMiddlewareService", { enumerable: true, get: function () { return middlewareService_1.MidwayMiddlewareService; } });
60
60
  var decoratorService_1 = require("./service/decoratorService");
61
61
  Object.defineProperty(exports, "MidwayDecoratorService", { enumerable: true, get: function () { return decoratorService_1.MidwayDecoratorService; } });
62
+ var mockService_1 = require("./service/mockService");
63
+ Object.defineProperty(exports, "MidwayMockService", { enumerable: true, get: function () { return mockService_1.MidwayMockService; } });
62
64
  __exportStar(require("./service/pipelineService"), exports);
63
65
  __exportStar(require("./util/contextUtil"), exports);
64
66
  __exportStar(require("./common/serviceFactory"), exports);
@@ -426,7 +426,6 @@ export interface IMidwayBootstrapOptions {
426
426
  globalConfig?: Array<{
427
427
  [environmentName: string]: Record<string, any>;
428
428
  }> | Record<string, any>;
429
- lazyInitializeFramework?: boolean;
430
429
  }
431
430
  export interface IConfigurationOptions {
432
431
  logger?: ILogger;
@@ -18,6 +18,7 @@ let MidwayMiddlewareService = class MidwayMiddlewareService {
18
18
  this.applicationContext = applicationContext;
19
19
  }
20
20
  async compose(middleware, app, name) {
21
+ var _a, _b;
21
22
  if (!Array.isArray(middleware)) {
22
23
  throw new error_1.MidwayParameterError('Middleware stack must be an array');
23
24
  }
@@ -42,8 +43,8 @@ let MidwayMiddlewareService = class MidwayMiddlewareService {
42
43
  // wrap ignore and match
43
44
  const mw = fn;
44
45
  const match = (0, util_1.pathMatching)({
45
- match: classMiddleware.match,
46
- ignore: classMiddleware.ignore,
46
+ match: (_a = classMiddleware.match) === null || _a === void 0 ? void 0 : _a.bind(classMiddleware),
47
+ ignore: (_b = classMiddleware.ignore) === null || _b === void 0 ? void 0 : _b.bind(classMiddleware),
47
48
  });
48
49
  fn = (ctx, next, options) => {
49
50
  if (!match(ctx))
@@ -0,0 +1,22 @@
1
+ import { IMidwayApplication, IMidwayContainer, IMidwayContext } from '../interface';
2
+ export declare class MidwayMockService {
3
+ readonly applicationContext: IMidwayContainer;
4
+ protected mocks: any[];
5
+ protected contextMocks: Array<{
6
+ app: IMidwayApplication;
7
+ key: string | ((ctx: IMidwayContext) => void);
8
+ value: any;
9
+ }>;
10
+ protected cache: Map<any, any>;
11
+ constructor(applicationContext: IMidwayContainer);
12
+ mockClassProperty(clzz: new (...args: any[]) => any, propertyName: string, value: any): void;
13
+ mockProperty(obj: any, key: string, value: any): void;
14
+ mockContext(app: IMidwayApplication, key: string | ((ctx: IMidwayContext) => void), value?: PropertyDescriptor | any): void;
15
+ restore(): void;
16
+ isMocked(obj: any, key: any): any;
17
+ applyContextMocks(app: IMidwayApplication, ctx: IMidwayContext): void;
18
+ getContextMocksSize(): number;
19
+ getMocksSize(): number;
20
+ private overridePropertyDescriptor;
21
+ }
22
+ //# sourceMappingURL=mockService.d.ts.map
@@ -0,0 +1,126 @@
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.MidwayMockService = void 0;
13
+ const decorator_1 = require("@midwayjs/decorator");
14
+ let MidwayMockService = class MidwayMockService {
15
+ constructor(applicationContext) {
16
+ this.applicationContext = applicationContext;
17
+ this.mocks = [];
18
+ this.contextMocks = [];
19
+ this.cache = new Map();
20
+ }
21
+ mockClassProperty(clzz, propertyName, value) {
22
+ return this.mockProperty(clzz.prototype, propertyName, value);
23
+ }
24
+ mockProperty(obj, key, value) {
25
+ // eslint-disable-next-line no-prototype-builtins
26
+ const hasOwnProperty = obj.hasOwnProperty(key);
27
+ this.mocks.push({
28
+ obj,
29
+ key,
30
+ descriptor: Object.getOwnPropertyDescriptor(obj, key),
31
+ // Make sure the key exists on object not the prototype
32
+ hasOwnProperty,
33
+ });
34
+ // Delete the origin key, redefine it below
35
+ if (hasOwnProperty) {
36
+ delete obj[key];
37
+ }
38
+ // Set a flag that checks if it is mocked
39
+ let flag = this.cache.get(obj);
40
+ if (!flag) {
41
+ flag = new Set();
42
+ this.cache.set(obj, flag);
43
+ }
44
+ flag.add(key);
45
+ const descriptor = this.overridePropertyDescriptor(value);
46
+ Object.defineProperty(obj, key, descriptor);
47
+ }
48
+ mockContext(app, key, value) {
49
+ this.contextMocks.push({
50
+ app,
51
+ key,
52
+ value,
53
+ });
54
+ }
55
+ restore() {
56
+ for (let i = this.mocks.length - 1; i >= 0; i--) {
57
+ const m = this.mocks[i];
58
+ if (!m.hasOwnProperty) {
59
+ // Delete the mock key, use key on the prototype
60
+ delete m.obj[m.key];
61
+ }
62
+ else {
63
+ // Redefine the origin key instead of the mock key
64
+ Object.defineProperty(m.obj, m.key, m.descriptor);
65
+ }
66
+ }
67
+ this.mocks = [];
68
+ this.contextMocks = [];
69
+ this.cache.clear();
70
+ }
71
+ isMocked(obj, key) {
72
+ const flag = this.cache.get(obj);
73
+ return flag ? flag.has(key) : false;
74
+ }
75
+ applyContextMocks(app, ctx) {
76
+ if (this.contextMocks.length > 0) {
77
+ for (const mockItem of this.contextMocks) {
78
+ if (mockItem.app === app) {
79
+ const descriptor = this.overridePropertyDescriptor(mockItem.value);
80
+ if (typeof mockItem.key === 'string') {
81
+ Object.defineProperty(ctx, mockItem.key, descriptor);
82
+ }
83
+ else {
84
+ mockItem.key(ctx);
85
+ }
86
+ }
87
+ }
88
+ }
89
+ }
90
+ getContextMocksSize() {
91
+ return this.contextMocks.length;
92
+ }
93
+ getMocksSize() {
94
+ return this.mocks.length;
95
+ }
96
+ overridePropertyDescriptor(value) {
97
+ const descriptor = {
98
+ configurable: true,
99
+ enumerable: true,
100
+ };
101
+ if (value && (value.get || value.set)) {
102
+ // Default to undefined
103
+ descriptor.get = value.get;
104
+ descriptor.set = value.set;
105
+ }
106
+ else {
107
+ // Without getter/setter mode
108
+ descriptor.value = value;
109
+ descriptor.writable = true;
110
+ }
111
+ return descriptor;
112
+ }
113
+ };
114
+ __decorate([
115
+ (0, decorator_1.Destroy)(),
116
+ __metadata("design:type", Function),
117
+ __metadata("design:paramtypes", []),
118
+ __metadata("design:returntype", void 0)
119
+ ], MidwayMockService.prototype, "restore", null);
120
+ MidwayMockService = __decorate([
121
+ (0, decorator_1.Provide)(),
122
+ (0, decorator_1.Scope)(decorator_1.ScopeEnum.Singleton),
123
+ __metadata("design:paramtypes", [Object])
124
+ ], MidwayMockService);
125
+ exports.MidwayMockService = MidwayMockService;
126
+ //# sourceMappingURL=mockService.js.map
package/dist/setup.d.ts CHANGED
@@ -1,4 +1,13 @@
1
1
  import { IMidwayBootstrapOptions, IMidwayContainer } from './';
2
+ /**
3
+ * midway framework main entry, this method bootstrap all service and framework.
4
+ * @param globalOptions
5
+ */
2
6
  export declare function initializeGlobalApplicationContext(globalOptions: IMidwayBootstrapOptions): Promise<IMidwayContainer>;
3
7
  export declare function destroyGlobalApplicationContext(applicationContext: IMidwayContainer): Promise<void>;
8
+ /**
9
+ * prepare applicationContext, it use in egg framework.
10
+ * @param globalOptions
11
+ */
12
+ export declare function prepareGlobalApplicationContext(globalOptions: IMidwayBootstrapOptions): IMidwayContainer;
4
13
  //# sourceMappingURL=setup.d.ts.map
package/dist/setup.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.destroyGlobalApplicationContext = exports.initializeGlobalApplicationContext = void 0;
3
+ exports.prepareGlobalApplicationContext = exports.destroyGlobalApplicationContext = exports.initializeGlobalApplicationContext = void 0;
4
4
  const _1 = require("./");
5
5
  const config_default_1 = require("./config/config.default");
6
6
  const decorator_1 = require("@midwayjs/decorator");
@@ -8,7 +8,55 @@ const util = require("util");
8
8
  const path_1 = require("path");
9
9
  const logger_1 = require("@midwayjs/logger");
10
10
  const debug = util.debuglog('midway:debug');
11
+ /**
12
+ * midway framework main entry, this method bootstrap all service and framework.
13
+ * @param globalOptions
14
+ */
11
15
  async function initializeGlobalApplicationContext(globalOptions) {
16
+ const applicationContext = prepareGlobalApplicationContext(globalOptions);
17
+ // init logger
18
+ const loggerService = await applicationContext.getAsync(_1.MidwayLoggerService, [
19
+ applicationContext,
20
+ ]);
21
+ if (loggerService.getLogger('appLogger')) {
22
+ // register global logger
23
+ applicationContext.registerObject('logger', loggerService.getLogger('appLogger'));
24
+ }
25
+ // framework/config/plugin/logger/app decorator support
26
+ await applicationContext.getAsync(_1.MidwayFrameworkService, [
27
+ applicationContext,
28
+ globalOptions,
29
+ ]);
30
+ // lifecycle support
31
+ await applicationContext.getAsync(_1.MidwayLifeCycleService, [
32
+ applicationContext,
33
+ ]);
34
+ // some preload module init
35
+ const modules = (0, decorator_1.listPreloadModule)();
36
+ for (const module of modules) {
37
+ // preload init context
38
+ await applicationContext.getAsync(module);
39
+ }
40
+ return applicationContext;
41
+ }
42
+ exports.initializeGlobalApplicationContext = initializeGlobalApplicationContext;
43
+ async function destroyGlobalApplicationContext(applicationContext) {
44
+ // stop lifecycle
45
+ const lifecycleService = await applicationContext.getAsync(_1.MidwayLifeCycleService);
46
+ await lifecycleService.stop();
47
+ // stop container
48
+ await applicationContext.stop();
49
+ (0, decorator_1.clearBindContainer)();
50
+ logger_1.loggers.close();
51
+ global['MIDWAY_APPLICATION_CONTEXT'] = undefined;
52
+ global['MIDWAY_MAIN_FRAMEWORK'] = undefined;
53
+ }
54
+ exports.destroyGlobalApplicationContext = destroyGlobalApplicationContext;
55
+ /**
56
+ * prepare applicationContext, it use in egg framework.
57
+ * @param globalOptions
58
+ */
59
+ function prepareGlobalApplicationContext(globalOptions) {
12
60
  var _a, _b, _c, _d;
13
61
  debug('[core]: start "initializeGlobalApplicationContext"');
14
62
  debug(`[core]: bootstrap options = ${util.inspect(globalOptions)}`);
@@ -46,6 +94,7 @@ async function initializeGlobalApplicationContext(globalOptions) {
46
94
  applicationContext.bindClass(_1.MidwayFrameworkService);
47
95
  applicationContext.bindClass(_1.MidwayMiddlewareService);
48
96
  applicationContext.bindClass(_1.MidwayLifeCycleService);
97
+ applicationContext.bindClass(_1.MidwayMockService);
49
98
  // bind preload module
50
99
  if (globalOptions.preloadModules && globalOptions.preloadModules.length) {
51
100
  for (const preloadModule of globalOptions.preloadModules) {
@@ -91,43 +140,7 @@ async function initializeGlobalApplicationContext(globalOptions) {
91
140
  debug('[core]: Current config = %j', configService.getConfiguration());
92
141
  // middleware support
93
142
  applicationContext.get(_1.MidwayMiddlewareService, [applicationContext]);
94
- // it will be delay framework initialize in egg cluster mode
95
- if (!globalOptions.lazyInitializeFramework) {
96
- // init logger
97
- const loggerService = await applicationContext.getAsync(_1.MidwayLoggerService, [applicationContext]);
98
- if (loggerService.getLogger('appLogger')) {
99
- // register global logger
100
- applicationContext.registerObject('logger', loggerService.getLogger('appLogger'));
101
- }
102
- // framework/config/plugin/logger/app decorator support
103
- await applicationContext.getAsync(_1.MidwayFrameworkService, [
104
- applicationContext,
105
- globalOptions,
106
- ]);
107
- // lifecycle support
108
- await applicationContext.getAsync(_1.MidwayLifeCycleService, [
109
- applicationContext,
110
- ]);
111
- // some preload module init
112
- const modules = (0, decorator_1.listPreloadModule)();
113
- for (const module of modules) {
114
- // preload init context
115
- await applicationContext.getAsync(module);
116
- }
117
- }
118
143
  return applicationContext;
119
144
  }
120
- exports.initializeGlobalApplicationContext = initializeGlobalApplicationContext;
121
- async function destroyGlobalApplicationContext(applicationContext) {
122
- // stop lifecycle
123
- const lifecycleService = await applicationContext.getAsync(_1.MidwayLifeCycleService);
124
- await lifecycleService.stop();
125
- // stop container
126
- await applicationContext.stop();
127
- (0, decorator_1.clearBindContainer)();
128
- logger_1.loggers.close();
129
- global['MIDWAY_APPLICATION_CONTEXT'] = undefined;
130
- global['MIDWAY_MAIN_FRAMEWORK'] = undefined;
131
- }
132
- exports.destroyGlobalApplicationContext = destroyGlobalApplicationContext;
145
+ exports.prepareGlobalApplicationContext = prepareGlobalApplicationContext;
133
146
  //# sourceMappingURL=setup.js.map
@@ -14,7 +14,13 @@ export interface IResponse extends http.IncomingMessage {
14
14
  status: number;
15
15
  data: Buffer | string | any;
16
16
  }
17
+ export declare function makeHttpRequest(url: string, options?: IOptions): Promise<IResponse>;
18
+ /**
19
+ * A simple http client
20
+ */
17
21
  export declare class HttpClient {
22
+ readonly defaultOptions: Pick<IOptions, 'headers' | 'timeout' | 'method'>;
23
+ constructor(defaultOptions?: Pick<IOptions, 'headers' | 'timeout' | 'method'>);
18
24
  request(url: string, options?: IOptions): Promise<IResponse>;
19
25
  }
20
26
  export {};
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HttpClient = void 0;
3
+ exports.HttpClient = exports.makeHttpRequest = void 0;
4
4
  const http = require("http");
5
5
  const https = require("https");
6
6
  const url = require("url");
@@ -13,80 +13,90 @@ const mimeMap = {
13
13
  json: 'application/json',
14
14
  octet: 'application/octet-stream',
15
15
  };
16
- class HttpClient {
17
- async request(url, options = {}) {
18
- debug(`request '${url}'`);
19
- const whatwgUrl = new URL(url);
20
- const client = whatwgUrl.protocol === 'https:' ? https : http;
21
- const contentType = options.contentType;
22
- const dataType = options.dataType;
23
- const method = options.method || 'GET';
24
- const timeout = options.timeout || 5000;
25
- const headers = {
26
- Accept: mimeMap[dataType] || mimeMap.octet,
27
- ...options.headers,
28
- };
29
- let data;
30
- if (method === 'GET' && options.data) {
31
- for (const key of Object.keys(options.data)) {
32
- whatwgUrl.searchParams.set(key, options.data[key]);
33
- }
34
- headers['Content-Length'] = 0;
35
- }
36
- else if (options.data) {
37
- data = Buffer.from(JSON.stringify(options.data));
38
- headers['Content-Type'] = mimeMap[contentType] || mimeMap.octet;
39
- headers['Content-Length'] = data.byteLength;
16
+ async function makeHttpRequest(url, options = {}) {
17
+ debug(`request '${url}'`);
18
+ const whatwgUrl = new URL(url);
19
+ const client = whatwgUrl.protocol === 'https:' ? https : http;
20
+ const contentType = options.contentType;
21
+ const dataType = options.dataType;
22
+ const method = options.method || 'GET';
23
+ const timeout = options.timeout || 5000;
24
+ const headers = {
25
+ Accept: mimeMap[dataType] || mimeMap.octet,
26
+ ...options.headers,
27
+ };
28
+ let data;
29
+ if (method === 'GET' && options.data) {
30
+ for (const key of Object.keys(options.data)) {
31
+ whatwgUrl.searchParams.set(key, options.data[key]);
40
32
  }
41
- return new Promise((resolve, reject) => {
42
- const req = client.request(whatwgUrl.toString(), {
43
- method,
44
- headers,
45
- }, res => {
46
- res.setTimeout(timeout, () => {
47
- res.destroy(new Error('Response Timeout'));
48
- });
49
- res.on('error', error => {
50
- reject(error);
51
- });
52
- const chunks = [];
53
- res.on('data', chunk => {
54
- chunks.push(chunk);
55
- });
56
- res.on('end', () => {
57
- let data = Buffer.concat(chunks);
58
- if (dataType === 'text' || dataType === 'json') {
59
- data = data.toString('utf8');
33
+ headers['Content-Length'] = 0;
34
+ }
35
+ else if (options.data) {
36
+ data = Buffer.from(JSON.stringify(options.data));
37
+ headers['Content-Type'] = mimeMap[contentType] || mimeMap.octet;
38
+ headers['Content-Length'] = data.byteLength;
39
+ }
40
+ return new Promise((resolve, reject) => {
41
+ const req = client.request(whatwgUrl.toString(), {
42
+ method,
43
+ headers,
44
+ }, res => {
45
+ res.setTimeout(timeout, () => {
46
+ res.destroy(new Error('Response Timeout'));
47
+ });
48
+ res.on('error', error => {
49
+ reject(error);
50
+ });
51
+ const chunks = [];
52
+ res.on('data', chunk => {
53
+ chunks.push(chunk);
54
+ });
55
+ res.on('end', () => {
56
+ let data = Buffer.concat(chunks);
57
+ if (dataType === 'text' || dataType === 'json') {
58
+ data = data.toString('utf8');
59
+ }
60
+ if (dataType === 'json') {
61
+ try {
62
+ data = JSON.parse(data);
60
63
  }
61
- if (dataType === 'json') {
62
- try {
63
- data = JSON.parse(data);
64
- }
65
- catch (e) {
66
- return reject(new Error('[httpclient] Unable to parse response data'));
67
- }
64
+ catch (e) {
65
+ return reject(new Error('[httpclient] Unable to parse response data'));
68
66
  }
69
- Object.assign(res, {
70
- status: res.statusCode,
71
- data,
72
- });
73
- debug(`request '${url}' resolved with status ${res.statusCode}`);
74
- resolve(res);
67
+ }
68
+ Object.assign(res, {
69
+ status: res.statusCode,
70
+ data,
75
71
  });
72
+ debug(`request '${url}' resolved with status ${res.statusCode}`);
73
+ resolve(res);
76
74
  });
77
- req.setTimeout(timeout, () => {
78
- req.destroy(new error_1.MidwayUtilHttpClientTimeoutError('Request Timeout'));
79
- });
80
- req.on('error', error => {
81
- reject(error);
82
- });
83
- if (method !== 'GET') {
84
- req.end(data);
85
- }
86
- else {
87
- req.end();
88
- }
89
75
  });
76
+ req.setTimeout(timeout, () => {
77
+ req.destroy(new error_1.MidwayUtilHttpClientTimeoutError('Request Timeout'));
78
+ });
79
+ req.on('error', error => {
80
+ reject(error);
81
+ });
82
+ if (method !== 'GET') {
83
+ req.end(data);
84
+ }
85
+ else {
86
+ req.end();
87
+ }
88
+ });
89
+ }
90
+ exports.makeHttpRequest = makeHttpRequest;
91
+ /**
92
+ * A simple http client
93
+ */
94
+ class HttpClient {
95
+ constructor(defaultOptions = {}) {
96
+ this.defaultOptions = defaultOptions;
97
+ }
98
+ async request(url, options) {
99
+ return makeHttpRequest(url, Object.assign(this.defaultOptions, options));
90
100
  }
91
101
  }
92
102
  exports.HttpClient = HttpClient;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/core",
3
- "version": "3.1.6",
3
+ "version": "3.2.2",
4
4
  "description": "midway core",
5
5
  "main": "dist/index",
6
6
  "typings": "dist/index.d.ts",
@@ -45,5 +45,5 @@
45
45
  "engines": {
46
46
  "node": ">=12"
47
47
  },
48
- "gitHead": "8c157a2b1a23ca2360522dc0de58513098952391"
48
+ "gitHead": "6bc097035302d01ae901d76a10e080db8554a864"
49
49
  }