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

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.
@@ -8,6 +8,7 @@ import { ContextMiddlewareManager } from './common/middlewareManager';
8
8
  import { MidwayMiddlewareService } from './service/middlewareService';
9
9
  import { FilterManager } from './common/filterManager';
10
10
  import { MidwayMockService } from './service/mockService';
11
+ import { AsyncContextManager } from './common/asyncContextManager';
11
12
  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> {
12
13
  readonly applicationContext: IMidwayContainer;
13
14
  app: APP;
@@ -20,6 +21,8 @@ export declare abstract class BaseFramework<APP extends IMidwayApplication<CTX>,
20
21
  protected middlewareManager: ContextMiddlewareManager<CTX, ResOrNext, Next>;
21
22
  protected filterManager: FilterManager<CTX, ResOrNext, Next>;
22
23
  protected composeMiddleware: any;
24
+ protected bootstrapOptions: IMidwayBootstrapOptions;
25
+ protected asyncContextManager: AsyncContextManager;
23
26
  loggerService: MidwayLoggerService;
24
27
  environmentService: MidwayEnvironmentService;
25
28
  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,38 @@ class BaseFramework {
231
233
  */
232
234
  async afterContainerReady(options) { }
233
235
  async applyMiddleware(lastMiddleware) {
236
+ var _a;
237
+ if (!this.applicationContext.hasObject(interface_1.ASYNC_CONTEXT_MANAGER_KEY)) {
238
+ const asyncContextManagerEnabled = this.configService.getConfiguration('asyncContextManager.enable') ||
239
+ false;
240
+ const contextManager = asyncContextManagerEnabled
241
+ ? ((_a = this.bootstrapOptions) === null || _a === void 0 ? void 0 : _a.contextManager) || new asyncContextManager_1.NoopContextManager()
242
+ : new asyncContextManager_1.NoopContextManager();
243
+ if (asyncContextManagerEnabled) {
244
+ contextManager.enable();
245
+ }
246
+ this.applicationContext.registerObject(interface_1.ASYNC_CONTEXT_MANAGER_KEY, contextManager);
247
+ }
234
248
  if (!this.composeMiddleware) {
235
249
  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;
250
+ // warp with context manager
251
+ const rootContext = asyncContextManager_1.ASYNC_ROOT_CONTEXT.setValue(interface_1.ASYNC_CONTEXT_KEY, ctx);
252
+ const contextManager = this.applicationContext.get(interface_1.ASYNC_CONTEXT_MANAGER_KEY);
253
+ return await contextManager.with(rootContext, async () => {
254
+ this.mockService.applyContextMocks(this.app, ctx);
255
+ let returnResult = undefined;
256
+ try {
257
+ const result = await next();
258
+ returnResult = await this.filterManager.runResultFilter(result, ctx);
259
+ }
260
+ catch (err) {
261
+ returnResult = await this.filterManager.runErrorFilter(err, ctx);
262
+ }
263
+ if (returnResult.error) {
264
+ throw returnResult.error;
265
+ }
266
+ return returnResult.result;
267
+ });
249
268
  }));
250
269
  debug(`[core]: Compose middleware = [${this.middlewareManager.getNames()}]`);
251
270
  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
@@ -1,7 +1,8 @@
1
1
  export declare abstract class DataSourceManager<T> {
2
2
  protected dataSource: Map<string, T>;
3
3
  protected options: {};
4
- protected initDataSource(options?: any): Promise<void>;
4
+ protected modelMapping: WeakMap<object, any>;
5
+ protected initDataSource(options: any, appDir: string): Promise<void>;
5
6
  /**
6
7
  * get a data source instance
7
8
  * @param dataSourceName
@@ -19,10 +20,16 @@ export declare abstract class DataSourceManager<T> {
19
20
  */
20
21
  isConnected(dataSourceName: string): Promise<boolean>;
21
22
  createInstance(config: any, clientName: any): Promise<T | void>;
23
+ /**
24
+ * get data source name by model or repository
25
+ * @param modelOrRepository
26
+ */
27
+ getDataSourceNameByModel(modelOrRepository: any): string | undefined;
22
28
  abstract getName(): string;
23
29
  protected abstract createDataSource(config: any, dataSourceName: string): Promise<T | void> | (T | void);
24
30
  protected abstract checkConnected(dataSource: T): Promise<boolean>;
25
31
  protected destroyDataSource(dataSource: T): Promise<void>;
26
32
  stop(): Promise<void>;
27
33
  }
34
+ export declare function globModels(globString: string, appDir: string): any[];
28
35
  //# sourceMappingURL=dataSourceManager.d.ts.map
@@ -1,22 +1,48 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DataSourceManager = void 0;
3
+ exports.globModels = exports.DataSourceManager = void 0;
4
4
  /**
5
5
  * 数据源管理器实现
6
6
  */
7
7
  const extend_1 = require("../util/extend");
8
8
  const error_1 = require("../error");
9
+ const glob_1 = require("@midwayjs/glob");
10
+ const path_1 = require("path");
11
+ const decorator_1 = require("@midwayjs/decorator");
12
+ const DEFAULT_PATTERN = ['**/**.ts', '**/**.js'];
9
13
  class DataSourceManager {
10
14
  constructor() {
11
15
  this.dataSource = new Map();
12
16
  this.options = {};
17
+ this.modelMapping = new WeakMap();
13
18
  }
14
- async initDataSource(options = {}) {
19
+ async initDataSource(options, appDir) {
15
20
  this.options = options;
16
21
  if (options.dataSource) {
17
22
  for (const dataSourceName in options.dataSource) {
23
+ const dataSourceOptions = options.dataSource[dataSourceName];
24
+ if (dataSourceOptions['entities']) {
25
+ const entities = new Set();
26
+ // loop entities and glob files to model
27
+ for (const entity of dataSourceOptions['entities']) {
28
+ if (typeof entity === 'string') {
29
+ // string will be glob file
30
+ const models = globModels(entity, appDir);
31
+ for (const model of models) {
32
+ entities.add(model);
33
+ this.modelMapping.set(model, dataSourceName);
34
+ }
35
+ }
36
+ else {
37
+ // model will be add to array
38
+ entities.add(entity);
39
+ this.modelMapping.set(entity, dataSourceName);
40
+ }
41
+ }
42
+ dataSourceOptions['entities'] = Array.from(entities);
43
+ }
18
44
  // create data source
19
- await this.createInstance(options.dataSource[dataSourceName], dataSourceName);
45
+ await this.createInstance(dataSourceOptions, dataSourceName);
20
46
  }
21
47
  }
22
48
  else {
@@ -58,12 +84,44 @@ class DataSourceManager {
58
84
  return client;
59
85
  }
60
86
  }
87
+ /**
88
+ * get data source name by model or repository
89
+ * @param modelOrRepository
90
+ */
91
+ getDataSourceNameByModel(modelOrRepository) {
92
+ return this.modelMapping.get(modelOrRepository);
93
+ }
61
94
  async destroyDataSource(dataSource) { }
62
95
  async stop() {
63
96
  for (const value of this.dataSource.values()) {
64
97
  await this.destroyDataSource(value);
65
98
  }
99
+ this.dataSource.clear();
66
100
  }
67
101
  }
68
102
  exports.DataSourceManager = DataSourceManager;
103
+ function globModels(globString, appDir) {
104
+ const cwd = (0, path_1.join)(appDir, globString);
105
+ const models = [];
106
+ // string will be glob file
107
+ const files = (0, glob_1.run)(DEFAULT_PATTERN, {
108
+ cwd,
109
+ });
110
+ for (const file of files) {
111
+ const exports = require(file);
112
+ if (decorator_1.Types.isClass(exports)) {
113
+ models.push(exports);
114
+ }
115
+ else {
116
+ for (const m in exports) {
117
+ const module = exports[m];
118
+ if (decorator_1.Types.isClass(module)) {
119
+ models.push(module);
120
+ }
121
+ }
122
+ }
123
+ }
124
+ return models;
125
+ }
126
+ exports.globModels = globModels;
69
127
  //# sourceMappingURL=dataSourceManager.js.map
@@ -1,15 +1,16 @@
1
- import { RouterInfo, IMidwayApplication } from '../index';
1
+ import { MidwayWebRouterService, RouterInfo, IMidwayApplication } from '../index';
2
2
  export declare abstract class WebControllerGenerator<Router extends {
3
3
  use: (...args: any[]) => void;
4
4
  }> {
5
5
  readonly app: IMidwayApplication;
6
- protected constructor(app: IMidwayApplication);
6
+ readonly midwayWebRouterService: MidwayWebRouterService;
7
+ protected constructor(app: IMidwayApplication, midwayWebRouterService: MidwayWebRouterService);
7
8
  /**
8
9
  * wrap controller string to middleware function
9
10
  * @param routeInfo
10
11
  */
11
12
  generateKoaController(routeInfo: RouterInfo): (ctx: any, next: any) => Promise<void>;
12
- loadMidwayController(globalPrefix: string, routerHandler?: (newRouter: Router) => void): Promise<void>;
13
+ loadMidwayController(routerHandler?: (newRouter: Router) => void): Promise<void>;
13
14
  abstract createRouter(routerOptions: any): Router;
14
15
  abstract generateController(routeInfo: RouterInfo): any;
15
16
  }
@@ -12,8 +12,9 @@ const index_1 = require("../index");
12
12
  const util = require("util");
13
13
  const debug = util.debuglog('midway:debug');
14
14
  class WebControllerGenerator {
15
- constructor(app) {
15
+ constructor(app, midwayWebRouterService) {
16
16
  this.app = app;
17
+ this.midwayWebRouterService = midwayWebRouterService;
17
18
  }
18
19
  /**
19
20
  * wrap controller string to middleware function
@@ -22,14 +23,24 @@ class WebControllerGenerator {
22
23
  generateKoaController(routeInfo) {
23
24
  return async (ctx, next) => {
24
25
  const args = [ctx, next];
25
- const controller = await ctx.requestContext.getAsync(routeInfo.id);
26
- // eslint-disable-next-line prefer-spread
27
- const result = await controller[routeInfo.method].apply(controller, args);
28
- if (result !== undefined) {
29
- ctx.body = result;
26
+ let result;
27
+ if (typeof routeInfo.method !== 'string') {
28
+ result = await routeInfo.method(ctx, next);
29
+ }
30
+ else {
31
+ const controller = await ctx.requestContext.getAsync(routeInfo.id);
32
+ // eslint-disable-next-line prefer-spread
33
+ result = await controller[routeInfo.method].apply(controller, args);
30
34
  }
31
- if (ctx.body === undefined && !ctx.response._explicitStatus) {
32
- ctx.body = undefined;
35
+ if (result !== undefined) {
36
+ if (result === null) {
37
+ // 这样设置可以绕过 koa 的 _explicitStatus 赋值机制
38
+ ctx.response._body = null;
39
+ ctx.response._midwayControllerNullBody = true;
40
+ }
41
+ else {
42
+ ctx.body = result;
43
+ }
33
44
  }
34
45
  // implement response decorator
35
46
  if (Array.isArray(routeInfo.responseMetadata) &&
@@ -56,13 +67,10 @@ class WebControllerGenerator {
56
67
  }
57
68
  };
58
69
  }
59
- async loadMidwayController(globalPrefix, routerHandler) {
70
+ async loadMidwayController(routerHandler) {
60
71
  var _a, _b;
61
- const collector = new index_1.WebRouterCollector('', {
62
- globalPrefix,
63
- });
64
- const routerTable = await collector.getRouterTable();
65
- const routerList = await collector.getRoutePriorityList();
72
+ const routerTable = await this.midwayWebRouterService.getRouterTable();
73
+ const routerList = await this.midwayWebRouterService.getRoutePriorityList();
66
74
  const applicationContext = this.app.getApplicationContext();
67
75
  const logger = this.app.getCoreLogger();
68
76
  const middlewareService = applicationContext.get(index_1.MidwayMiddlewareService);
@@ -93,6 +101,7 @@ class WebControllerGenerator {
93
101
  methodMiddlewares.push(routeMiddlewareFn);
94
102
  }
95
103
  if (this.app.getFrameworkType() === decorator_1.MidwayFrameworkType.WEB_KOA) {
104
+ // egg use path-to-regexp v1 but koa use v6
96
105
  if (typeof routeInfo.url === 'string' && /\*$/.test(routeInfo.url)) {
97
106
  routeInfo.url = routeInfo.url.replace('*', '(.*)');
98
107
  }
@@ -107,7 +116,7 @@ class WebControllerGenerator {
107
116
  debug(`[core]: Load Router "${routeInfo.requestMethod.toUpperCase()} ${routeInfo.url}"`);
108
117
  // apply controller from request context
109
118
  // eslint-disable-next-line prefer-spread
110
- newRouter[routeInfo.requestMethod].apply(newRouter, routerArgs);
119
+ newRouter[routeInfo.requestMethod.toLowerCase()].apply(newRouter, routerArgs);
111
120
  }
112
121
  routerHandler && routerHandler(newRouter);
113
122
  }
@@ -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),
@@ -17,6 +17,7 @@ export declare const FrameworkErrorEnum: {
17
17
  readonly INCONSISTENT_VERSION: "MIDWAY_10013";
18
18
  readonly INVALID_CONFIG: "MIDWAY_10014";
19
19
  readonly DUPLICATE_CLASS_NAME: "MIDWAY_10015";
20
+ readonly DUPLICATE_CONTROLLER_PREFIX_OPTIONS: "MIDWAY_10016";
20
21
  };
21
22
  export declare class MidwayCommonError extends MidwayError {
22
23
  constructor(message: string);
@@ -66,4 +67,7 @@ export declare class MidwayInconsistentVersionError extends MidwayError {
66
67
  export declare class MidwayDuplicateClassNameError extends MidwayError {
67
68
  constructor(className: string, existPath: string, existPathOther: string);
68
69
  }
70
+ export declare class MidwayDuplicateControllerOptionsError extends MidwayError {
71
+ constructor(prefix: string, existController: string, existControllerOther: string);
72
+ }
69
73
  //# sourceMappingURL=framework.d.ts.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- 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.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,
@@ -19,6 +19,7 @@ exports.FrameworkErrorEnum = (0, base_1.registerErrorCode)('midway', {
19
19
  INCONSISTENT_VERSION: 10013,
20
20
  INVALID_CONFIG: 10014,
21
21
  DUPLICATE_CLASS_NAME: 10015,
22
+ DUPLICATE_CONTROLLER_PREFIX_OPTIONS: 10016,
22
23
  });
23
24
  class MidwayCommonError extends base_1.MidwayError {
24
25
  constructor(message) {
@@ -129,4 +130,10 @@ class MidwayDuplicateClassNameError extends base_1.MidwayError {
129
130
  }
130
131
  }
131
132
  exports.MidwayDuplicateClassNameError = MidwayDuplicateClassNameError;
133
+ class MidwayDuplicateControllerOptionsError extends base_1.MidwayError {
134
+ constructor(prefix, existController, existControllerOther) {
135
+ super(`"Prefix ${prefix}" with duplicated controller options between "${existController}" and "${existControllerOther}"`, exports.FrameworkErrorEnum.DUPLICATE_CONTROLLER_PREFIX_OPTIONS);
136
+ }
137
+ }
138
+ exports.MidwayDuplicateControllerOptionsError = MidwayDuplicateControllerOptionsError;
132
139
  //# sourceMappingURL=framework.js.map
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
  }