@midwayjs/core 3.4.0-beta.8 → 3.4.0-beta.9

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.
@@ -20,6 +20,7 @@ export declare abstract class BaseFramework<APP extends IMidwayApplication<CTX>,
20
20
  protected middlewareManager: ContextMiddlewareManager<CTX, ResOrNext, Next>;
21
21
  protected filterManager: FilterManager<CTX, ResOrNext, Next>;
22
22
  protected composeMiddleware: any;
23
+ protected bootstrapOptions: IMidwayBootstrapOptions;
23
24
  loggerService: MidwayLoggerService;
24
25
  environmentService: MidwayEnvironmentService;
25
26
  configService: MidwayConfigService;
@@ -22,6 +22,7 @@ const middlewareService_1 = require("./service/middlewareService");
22
22
  const filterManager_1 = require("./common/filterManager");
23
23
  const mockService_1 = require("./service/mockService");
24
24
  const util = require("util");
25
+ const asyncContextManager_1 = require("./common/asyncContextManager");
25
26
  const debug = util.debuglog('midway:debug');
26
27
  class BaseFramework {
27
28
  constructor(applicationContext) {
@@ -45,6 +46,7 @@ class BaseFramework {
45
46
  return true;
46
47
  }
47
48
  async initialize(options) {
49
+ this.bootstrapOptions = options;
48
50
  await this.beforeContainerInitialize(options);
49
51
  await this.containerInitialize(options);
50
52
  await this.afterContainerInitialize(options);
@@ -231,21 +233,34 @@ class BaseFramework {
231
233
  */
232
234
  async afterContainerReady(options) { }
233
235
  async applyMiddleware(lastMiddleware) {
236
+ var _a;
237
+ const asyncContextManagerEnabled = this.configService.getConfiguration('asyncContextManager.enable') ||
238
+ false;
239
+ const contextManager = asyncContextManagerEnabled
240
+ ? ((_a = this.bootstrapOptions) === null || _a === void 0 ? void 0 : _a.contextManager) || new asyncContextManager_1.NoopContextManager()
241
+ : new asyncContextManager_1.NoopContextManager();
242
+ if (asyncContextManagerEnabled) {
243
+ contextManager.enable();
244
+ }
234
245
  if (!this.composeMiddleware) {
235
246
  this.middlewareManager.insertFirst((async (ctx, next) => {
236
- this.mockService.applyContextMocks(this.app, ctx);
237
- let returnResult = undefined;
238
- try {
239
- const result = await next();
240
- returnResult = await this.filterManager.runResultFilter(result, ctx);
241
- }
242
- catch (err) {
243
- returnResult = await this.filterManager.runErrorFilter(err, ctx);
244
- }
245
- if (returnResult.error) {
246
- throw returnResult.error;
247
- }
248
- return returnResult.result;
247
+ // warp with context manager
248
+ const rootContext = asyncContextManager_1.ASYNC_ROOT_CONTEXT.setValue(interface_1.ASYNC_CONTEXT_KEY, ctx);
249
+ return await contextManager.with(rootContext, async () => {
250
+ this.mockService.applyContextMocks(this.app, ctx);
251
+ let returnResult = undefined;
252
+ try {
253
+ const result = await next();
254
+ returnResult = await this.filterManager.runResultFilter(result, ctx);
255
+ }
256
+ catch (err) {
257
+ returnResult = await this.filterManager.runErrorFilter(err, ctx);
258
+ }
259
+ if (returnResult.error) {
260
+ throw returnResult.error;
261
+ }
262
+ return returnResult.result;
263
+ });
249
264
  }));
250
265
  debug(`[core]: Compose middleware = [${this.middlewareManager.getNames()}]`);
251
266
  this.composeMiddleware = await this.middlewareService.compose(this.middlewareManager, this.app);
@@ -0,0 +1,61 @@
1
+ export interface AsyncContext {
2
+ /**
3
+ * Get a value from the context.
4
+ *
5
+ * @param key key which identifies a context value
6
+ */
7
+ getValue(key: symbol): unknown;
8
+ /**
9
+ * Create a new context which inherits from this context and has
10
+ * the given key set to the given value.
11
+ *
12
+ * @param key context key for which to set the value
13
+ * @param value value to set for the given key
14
+ */
15
+ setValue(key: symbol, value: unknown): AsyncContext;
16
+ /**
17
+ * Return a new context which inherits from this context but does
18
+ * not contain a value for the given key.
19
+ *
20
+ * @param key context key for which to clear a value
21
+ */
22
+ deleteValue(key: symbol): AsyncContext;
23
+ }
24
+ export interface AsyncContextManager {
25
+ /**
26
+ * Get the current active context
27
+ */
28
+ active(): AsyncContext;
29
+ /**
30
+ * Run the fn callback with object set as the current active context
31
+ * @param context Any object to set as the current active context
32
+ * @param fn A callback to be immediately run within a specific context
33
+ * @param thisArg optional receiver to be used for calling fn
34
+ * @param args optional arguments forwarded to fn
35
+ */
36
+ with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(context: AsyncContext, fn: F, thisArg?: ThisParameterType<F>, ...args: A): ReturnType<F>;
37
+ /**
38
+ * Bind an object as the current context (or a specific one)
39
+ * @param [context] Optionally specify the context which you want to assign
40
+ * @param target Any object to which a context need to be set
41
+ */
42
+ bind<T>(context: AsyncContext, target: T): T;
43
+ /**
44
+ * Enable context management
45
+ */
46
+ enable(): this;
47
+ /**
48
+ * Disable context management
49
+ */
50
+ disable(): this;
51
+ }
52
+ /** The root context is used as the default parent context when there is no active context */
53
+ export declare const ASYNC_ROOT_CONTEXT: AsyncContext;
54
+ export declare class NoopContextManager implements AsyncContextManager {
55
+ active(): AsyncContext;
56
+ with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(_context: AsyncContext, fn: F, thisArg?: ThisParameterType<F>, ...args: A): ReturnType<F>;
57
+ bind<T>(_context: AsyncContext, target: T): T;
58
+ enable(): this;
59
+ disable(): this;
60
+ }
61
+ //# sourceMappingURL=asyncContextManager.d.ts.map
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright The OpenTelemetry Authors
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.NoopContextManager = exports.ASYNC_ROOT_CONTEXT = void 0;
19
+ class AsyncBaseContext {
20
+ /**
21
+ * Construct a new context which inherits values from an optional parent context.
22
+ *
23
+ * @param parentContext a context from which to inherit values
24
+ */
25
+ constructor(parentContext) {
26
+ // for minification
27
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
28
+ const self = this;
29
+ self._currentContext = parentContext ? new Map(parentContext) : new Map();
30
+ self.getValue = (key) => self._currentContext.get(key);
31
+ self.setValue = (key, value) => {
32
+ const context = new AsyncBaseContext(self._currentContext);
33
+ context._currentContext.set(key, value);
34
+ return context;
35
+ };
36
+ self.deleteValue = (key) => {
37
+ const context = new AsyncBaseContext(self._currentContext);
38
+ context._currentContext.delete(key);
39
+ return context;
40
+ };
41
+ }
42
+ }
43
+ /** The root context is used as the default parent context when there is no active context */
44
+ exports.ASYNC_ROOT_CONTEXT = new AsyncBaseContext();
45
+ class NoopContextManager {
46
+ active() {
47
+ return exports.ASYNC_ROOT_CONTEXT;
48
+ }
49
+ with(_context, fn, thisArg, ...args) {
50
+ return fn.call(thisArg, ...args);
51
+ }
52
+ bind(_context, target) {
53
+ return target;
54
+ }
55
+ enable() {
56
+ return this;
57
+ }
58
+ disable() {
59
+ return this;
60
+ }
61
+ }
62
+ exports.NoopContextManager = NoopContextManager;
63
+ //# sourceMappingURL=asyncContextManager.js.map
@@ -5,6 +5,9 @@ declare const _default: (appInfo: MidwayAppInfo) => {
5
5
  debug?: {
6
6
  recordConfigMergeOrder?: boolean;
7
7
  };
8
+ asyncContextManager: {
9
+ enable: boolean;
10
+ };
8
11
  };
9
12
  export default _default;
10
13
  //# sourceMappingURL=config.default.d.ts.map
@@ -8,6 +8,9 @@ exports.default = (appInfo) => {
8
8
  const isDevelopment = (0, util_1.isDevelopmentEnvironment)((0, util_1.getCurrentEnvironment)());
9
9
  const logRoot = (_a = process.env[interface_1.MIDWAY_LOGGER_WRITEABLE_DIR]) !== null && _a !== void 0 ? _a : appInfo.root;
10
10
  return {
11
+ asyncContextManager: {
12
+ enable: false,
13
+ },
11
14
  midwayLogger: {
12
15
  default: {
13
16
  dir: (0, path_1.join)(logRoot, 'logs', appInfo.name),
package/dist/index.d.ts CHANGED
@@ -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.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;
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");
@@ -81,6 +81,8 @@ __exportStar(require("./common/filterManager"), exports);
81
81
  __exportStar(require("./common/applicationManager"), exports);
82
82
  __exportStar(require("./setup"), exports);
83
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; } });
84
86
  /**
85
87
  * proxy
86
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
  };
@@ -432,6 +433,7 @@ export interface IMidwayBootstrapOptions {
432
433
  globalConfig?: Array<{
433
434
  [environmentName: string]: Record<string, any>;
434
435
  }> | Record<string, any>;
436
+ asyncContextManager?: AsyncContextManager;
435
437
  }
436
438
  export interface IConfigurationOptions {
437
439
  logger?: ILogger;
@@ -479,5 +481,6 @@ export interface MidwayAppInfo {
479
481
  export interface MidwayConfig extends FileConfigOption<typeof _default> {
480
482
  [customConfigKey: string]: unknown;
481
483
  }
484
+ export declare const ASYNC_CONTEXT_KEY: unique symbol;
482
485
  export {};
483
486
  //# 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_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,5 @@ 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');
22
23
  //# sourceMappingURL=interface.js.map
@@ -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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/core",
3
- "version": "3.4.0-beta.8",
3
+ "version": "3.4.0-beta.9",
4
4
  "description": "midway core",
5
5
  "main": "dist/index",
6
6
  "typings": "dist/index.d.ts",
@@ -21,7 +21,7 @@
21
21
  ],
22
22
  "license": "MIT",
23
23
  "devDependencies": {
24
- "@midwayjs/decorator": "^3.4.0-beta.8",
24
+ "@midwayjs/decorator": "^3.4.0-beta.9",
25
25
  "koa": "2.13.4",
26
26
  "midway-test-component": "*",
27
27
  "mm": "3.2.0",
@@ -45,5 +45,5 @@
45
45
  "engines": {
46
46
  "node": ">=12"
47
47
  },
48
- "gitHead": "9e4ed69eca31022e4dc93ed52ac503fe25ae383e"
48
+ "gitHead": "41e82a0fba386c6ec42c2eefd1dff4795a81b389"
49
49
  }