@midwayjs/core 3.4.6 → 3.4.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.
@@ -1,4 +1,4 @@
1
- import { CommonMiddlewareUnion, IConfigurationOptions, IMidwayApplication, IMidwayBootstrapOptions, IMidwayContainer, IMidwayContext, IMidwayFramework, CommonFilterUnion, CommonMiddleware, MiddlewareRespond } from './interface';
1
+ import { CommonMiddlewareUnion, IConfigurationOptions, IMidwayApplication, IMidwayBootstrapOptions, IMidwayContainer, IMidwayContext, IMidwayFramework, CommonFilterUnion, MiddlewareRespond } from './interface';
2
2
  import { ILogger, LoggerOptions, LoggerContextFormat } from '@midwayjs/logger';
3
3
  import { MidwayEnvironmentService } from './service/environmentService';
4
4
  import { MidwayConfigService } from './service/configService';
@@ -74,7 +74,7 @@ export declare abstract class BaseFramework<APP extends IMidwayApplication<CTX>,
74
74
  * @deprecated
75
75
  */
76
76
  protected afterContainerReady(options: Partial<IMidwayBootstrapOptions>): Promise<void>;
77
- applyMiddleware<R, N>(lastMiddleware?: CommonMiddleware<CTX, R, N>): Promise<MiddlewareRespond<CTX, R, N>>;
77
+ applyMiddleware<R, N>(lastMiddleware?: CommonMiddlewareUnion<CTX, R, N>): Promise<MiddlewareRespond<CTX, R, N>>;
78
78
  getLogger(name?: string): ILogger;
79
79
  getCoreLogger(): ILogger;
80
80
  createLogger(name: string, option?: LoggerOptions): ILogger;
@@ -234,18 +234,19 @@ class BaseFramework {
234
234
  async afterContainerReady(options) { }
235
235
  async applyMiddleware(lastMiddleware) {
236
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.asyncContextManager) || 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
- }
248
237
  if (!this.composeMiddleware) {
238
+ if (!this.applicationContext.hasObject(interface_1.ASYNC_CONTEXT_MANAGER_KEY)) {
239
+ const asyncContextManagerEnabled = this.configService.getConfiguration('asyncContextManager.enable') ||
240
+ false;
241
+ const contextManager = asyncContextManagerEnabled
242
+ ? ((_a = this.bootstrapOptions) === null || _a === void 0 ? void 0 : _a.asyncContextManager) ||
243
+ new asyncContextManager_1.NoopContextManager()
244
+ : new asyncContextManager_1.NoopContextManager();
245
+ if (asyncContextManagerEnabled) {
246
+ contextManager.enable();
247
+ }
248
+ this.applicationContext.registerObject(interface_1.ASYNC_CONTEXT_MANAGER_KEY, contextManager);
249
+ }
249
250
  this.middlewareManager.insertFirst((async (ctx, next) => {
250
251
  // warp with context manager
251
252
  const rootContext = asyncContextManager_1.ASYNC_ROOT_CONTEXT.setValue(interface_1.ASYNC_CONTEXT_KEY, ctx);
@@ -271,11 +272,12 @@ class BaseFramework {
271
272
  await this.filterManager.init(this.applicationContext);
272
273
  }
273
274
  if (lastMiddleware) {
274
- return await this.middlewareService.compose([this.composeMiddleware, lastMiddleware], this.app);
275
- }
276
- else {
277
- return this.composeMiddleware;
275
+ lastMiddleware = Array.isArray(lastMiddleware)
276
+ ? lastMiddleware
277
+ : [lastMiddleware];
278
+ return await this.middlewareService.compose([this.composeMiddleware, ...lastMiddleware], this.app);
278
279
  }
280
+ return this.composeMiddleware;
279
281
  }
280
282
  getLogger(name) {
281
283
  var _a;
@@ -19,7 +19,7 @@ export declare abstract class DataSourceManager<T> {
19
19
  * @param dataSourceName
20
20
  */
21
21
  isConnected(dataSourceName: string): Promise<boolean>;
22
- createInstance(config: any, clientName: any): Promise<T | void>;
22
+ createInstance(config: any, clientName: any, options?: CreateInstanceOptions): Promise<T | void>;
23
23
  /**
24
24
  * get data source name by model or repository
25
25
  * @param modelOrRepository
@@ -32,4 +32,7 @@ export declare abstract class DataSourceManager<T> {
32
32
  stop(): Promise<void>;
33
33
  }
34
34
  export declare function globModels(globString: string, appDir: string): any[];
35
+ export interface CreateInstanceOptions {
36
+ cacheInstance?: boolean | undefined;
37
+ }
35
38
  //# sourceMappingURL=dataSourceManager.d.ts.map
@@ -9,7 +9,7 @@ const error_1 = require("../error");
9
9
  const glob_1 = require("@midwayjs/glob");
10
10
  const path_1 = require("path");
11
11
  const decorator_1 = require("@midwayjs/decorator");
12
- const DEFAULT_PATTERN = ['**/**.ts', '**/**.js'];
12
+ const interface_1 = require("../interface");
13
13
  class DataSourceManager {
14
14
  constructor() {
15
15
  this.dataSource = new Map();
@@ -18,35 +18,36 @@ class DataSourceManager {
18
18
  }
19
19
  async initDataSource(options, appDir) {
20
20
  this.options = options;
21
- if (options.dataSource) {
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);
21
+ if (!options.dataSource) {
22
+ throw new error_1.MidwayParameterError('DataSourceManager must set options.dataSource.');
23
+ }
24
+ for (const dataSourceName in options.dataSource) {
25
+ const dataSourceOptions = options.dataSource[dataSourceName];
26
+ if (dataSourceOptions['entities']) {
27
+ const entities = new Set();
28
+ // loop entities and glob files to model
29
+ for (const entity of dataSourceOptions['entities']) {
30
+ if (typeof entity === 'string') {
31
+ // string will be glob file
32
+ const models = globModels(entity, appDir);
33
+ for (const model of models) {
34
+ entities.add(model);
35
+ this.modelMapping.set(model, dataSourceName);
40
36
  }
41
37
  }
42
- dataSourceOptions['entities'] = Array.from(entities);
38
+ else {
39
+ // model will be add to array
40
+ entities.add(entity);
41
+ this.modelMapping.set(entity, dataSourceName);
42
+ }
43
43
  }
44
- // create data source
45
- await this.createInstance(dataSourceOptions, dataSourceName);
44
+ dataSourceOptions['entities'] = Array.from(entities);
46
45
  }
47
- }
48
- else {
49
- throw new error_1.MidwayParameterError('DataSourceManager must set options.dataSource.');
46
+ // create data source
47
+ const opts = {
48
+ cacheInstance: options.cacheInstance, // will default true
49
+ };
50
+ await this.createInstance(dataSourceOptions, dataSourceName, opts);
50
51
  }
51
52
  }
52
53
  /**
@@ -71,18 +72,20 @@ class DataSourceManager {
71
72
  * @param dataSourceName
72
73
  */
73
74
  async isConnected(dataSourceName) {
74
- return this.checkConnected(this.getDataSource(dataSourceName));
75
+ const inst = this.getDataSource(dataSourceName);
76
+ return inst ? this.checkConnected(inst) : false;
75
77
  }
76
- async createInstance(config, clientName) {
78
+ async createInstance(config, clientName, options) {
79
+ const cache = options && typeof options.cacheInstance === 'boolean'
80
+ ? options.cacheInstance
81
+ : true;
77
82
  // options.default will be merge in to options.clients[id]
78
- config = (0, extend_1.extend)(true, {}, this.options['default'], config);
79
- const client = await this.createDataSource(config, clientName);
80
- if (client) {
81
- if (clientName) {
82
- this.dataSource.set(clientName, client);
83
- }
84
- return client;
83
+ const configNow = (0, extend_1.extend)(true, {}, this.options['default'], config);
84
+ const client = await this.createDataSource(configNow, clientName);
85
+ if (cache && clientName && client) {
86
+ this.dataSource.set(clientName, client);
85
87
  }
88
+ return client;
86
89
  }
87
90
  /**
88
91
  * get data source name by model or repository
@@ -104,8 +107,9 @@ function globModels(globString, appDir) {
104
107
  const cwd = (0, path_1.join)(appDir, globString);
105
108
  const models = [];
106
109
  // string will be glob file
107
- const files = (0, glob_1.run)(DEFAULT_PATTERN, {
110
+ const files = (0, glob_1.run)(interface_1.DEFAULT_PATTERN, {
108
111
  cwd,
112
+ ignore: interface_1.IGNORE_PATTERN,
109
113
  });
110
114
  for (const file of files) {
111
115
  const exports = require(file);
@@ -7,19 +7,18 @@ export declare abstract class AbstractFileDetector<T> implements IFileDetector {
7
7
  setExtraDetectorOptions(detectorOptions: T): void;
8
8
  }
9
9
  export declare class DirectoryFileDetector extends AbstractFileDetector<{
10
- loadDir: string | string[];
11
- pattern: string | string[];
12
- ignore: string | string[];
13
- namespace: string;
14
- conflictCheck: boolean;
10
+ loadDir?: string | string[];
11
+ pattern?: string | string[];
12
+ ignore?: string | string[];
13
+ namespace?: string;
14
+ conflictCheck?: boolean;
15
15
  }> {
16
- private directoryFilterArray;
17
16
  private duplicateModuleCheckSet;
18
17
  run(container: any): void;
19
18
  }
20
19
  export declare class CustomModuleDetector extends AbstractFileDetector<{
21
- modules: any[];
22
- namespace: string;
20
+ modules?: any[];
21
+ namespace?: string;
23
22
  }> {
24
23
  run(container: any): void;
25
24
  }
@@ -4,6 +4,7 @@ exports.CustomModuleDetector = exports.DirectoryFileDetector = exports.AbstractF
4
4
  const decorator_1 = require("@midwayjs/decorator");
5
5
  const glob_1 = require("@midwayjs/glob");
6
6
  const error_1 = require("../error");
7
+ const interface_1 = require("../interface");
7
8
  class AbstractFileDetector {
8
9
  constructor(options) {
9
10
  this.options = options;
@@ -14,9 +15,8 @@ class AbstractFileDetector {
14
15
  }
15
16
  }
16
17
  exports.AbstractFileDetector = AbstractFileDetector;
17
- const DEFAULT_PATTERN = ['**/**.ts', '**/**.tsx', '**/**.js'];
18
+ const DEFAULT_GLOB_PATTERN = ['**/**.tsx'].concat(interface_1.DEFAULT_PATTERN);
18
19
  const DEFAULT_IGNORE_PATTERN = [
19
- '**/**.d.ts',
20
20
  '**/logs/**',
21
21
  '**/run/**',
22
22
  '**/public/**',
@@ -27,11 +27,10 @@ const DEFAULT_IGNORE_PATTERN = [
27
27
  '**/**.test.ts',
28
28
  '**/**.test.js',
29
29
  '**/__test__/**',
30
- ];
30
+ ].concat(interface_1.IGNORE_PATTERN);
31
31
  class DirectoryFileDetector extends AbstractFileDetector {
32
32
  constructor() {
33
33
  super(...arguments);
34
- this.directoryFilterArray = [];
35
34
  this.duplicateModuleCheckSet = new Map();
36
35
  }
37
36
  run(container) {
@@ -39,13 +38,15 @@ class DirectoryFileDetector extends AbstractFileDetector {
39
38
  .concat(this.options.loadDir || [])
40
39
  .concat(this.extraDetectorOptions.loadDir || []);
41
40
  for (const dir of loadDirs) {
42
- const fileResults = (0, glob_1.run)(DEFAULT_PATTERN.concat(this.options.pattern || []).concat(this.extraDetectorOptions.pattern || []), {
41
+ const fileResults = (0, glob_1.run)(DEFAULT_GLOB_PATTERN.concat(this.options.pattern || []).concat(this.extraDetectorOptions.pattern || []), {
43
42
  cwd: dir,
44
43
  ignore: DEFAULT_IGNORE_PATTERN.concat(this.options.ignore || []).concat(this.extraDetectorOptions.ignore || []),
45
44
  });
46
45
  // 检查重复模块
47
46
  const checkDuplicatedHandler = (module, options) => {
48
- if (this.extraDetectorOptions.conflictCheck && decorator_1.Types.isClass(module)) {
47
+ if ((this.options.conflictCheck ||
48
+ this.extraDetectorOptions.conflictCheck) &&
49
+ decorator_1.Types.isClass(module)) {
49
50
  const name = (0, decorator_1.getProviderName)(module);
50
51
  if (name) {
51
52
  if (this.duplicateModuleCheckSet.has(name)) {
@@ -58,46 +59,14 @@ class DirectoryFileDetector extends AbstractFileDetector {
58
59
  }
59
60
  };
60
61
  for (const file of fileResults) {
61
- if (this.directoryFilterArray.length) {
62
- for (const resolveFilter of this.directoryFilterArray) {
63
- if (typeof resolveFilter.pattern === 'string') {
64
- if (file.includes(resolveFilter.pattern)) {
65
- const exports = resolveFilter.ignoreRequire
66
- ? undefined
67
- : require(file);
68
- resolveFilter.filter(exports, file, this);
69
- continue;
70
- }
71
- }
72
- else if (decorator_1.Types.isRegExp(resolveFilter.pattern)) {
73
- if (resolveFilter.pattern.test(file)) {
74
- const exports = resolveFilter.ignoreRequire
75
- ? undefined
76
- : require(file);
77
- resolveFilter.filter(exports, file, this);
78
- continue;
79
- }
80
- }
81
- const exports = require(file);
82
- // add module to set
83
- container.bindClass(exports, {
84
- namespace: this.options.namespace,
85
- srcPath: file,
86
- createFrom: 'file',
87
- bindHook: checkDuplicatedHandler,
88
- });
89
- }
90
- }
91
- else {
92
- const exports = require(file);
93
- // add module to set
94
- container.bindClass(exports, {
95
- namespace: this.options.namespace,
96
- srcPath: file,
97
- createFrom: 'file',
98
- bindHook: checkDuplicatedHandler,
99
- });
100
- }
62
+ const exports = require(file);
63
+ // add module to set
64
+ container.bindClass(exports, {
65
+ namespace: this.options.namespace,
66
+ srcPath: file,
67
+ createFrom: 'file',
68
+ bindHook: checkDuplicatedHandler,
69
+ });
101
70
  }
102
71
  }
103
72
  // check end
@@ -60,6 +60,8 @@ export declare class ContextMiddlewareManager<CTX extends IMidwayContext, R, N>
60
60
  * @param middlewareOrNameOrIdx
61
61
  */
62
62
  remove(middlewareOrNameOrIdx: CommonMiddleware<CTX, R, N> | string | number): CommonMiddleware<CTX, R, N>;
63
+ push(...items: any[]): number;
64
+ unshift(...items: any[]): number;
63
65
  /**
64
66
  * get middleware name list
65
67
  */
@@ -170,6 +170,22 @@ class ContextMiddlewareManager extends Array {
170
170
  }
171
171
  }
172
172
  }
173
+ push(...items) {
174
+ items.forEach(item => {
175
+ if (typeof item !== 'string' && !this.getMiddlewareName(item)) {
176
+ item._name = 'anonymous';
177
+ }
178
+ });
179
+ return super.push(...items);
180
+ }
181
+ unshift(...items) {
182
+ items.forEach(item => {
183
+ if (typeof item !== 'string' && !this.getMiddlewareName(item)) {
184
+ item._name = 'anonymous';
185
+ }
186
+ });
187
+ return super.unshift(...items);
188
+ }
173
189
  /**
174
190
  * get middleware name list
175
191
  */
@@ -46,6 +46,9 @@ class MidwayHttpError extends MidwayError {
46
46
  ? resOrMessage
47
47
  : resOrMessage.message
48
48
  : http_1.STATUS_CODES[status], code !== null && code !== void 0 ? code : String(status), options);
49
+ if (resOrMessage && resOrMessage['stack']) {
50
+ this.stack = resOrMessage['stack'];
51
+ }
49
52
  this.status = status;
50
53
  }
51
54
  }
@@ -462,7 +462,7 @@ export interface IMidwayFramework<APP extends IMidwayApplication<CTX>, CTX exten
462
462
  getProjectName(): string;
463
463
  useMiddleware(Middleware: CommonMiddlewareUnion<CTX, ResOrNext, Next>): void;
464
464
  getMiddleware(): ContextMiddlewareManager<CTX, ResOrNext, Next>;
465
- applyMiddleware(lastMiddleware?: CommonMiddleware<CTX, ResOrNext, Next>): Promise<MiddlewareRespond<CTX, ResOrNext, Next>>;
465
+ applyMiddleware(lastMiddleware?: CommonMiddlewareUnion<CTX, ResOrNext, Next>): Promise<MiddlewareRespond<CTX, ResOrNext, Next>>;
466
466
  useFilter(Filter: CommonFilterUnion<CTX, ResOrNext, Next>): any;
467
467
  }
468
468
  export declare const MIDWAY_LOGGER_WRITEABLE_DIR = "MIDWAY_LOGGER_WRITEABLE_DIR";
@@ -483,5 +483,7 @@ export interface MidwayConfig extends FileConfigOption<typeof _default> {
483
483
  }
484
484
  export declare const ASYNC_CONTEXT_KEY: unique symbol;
485
485
  export declare const ASYNC_CONTEXT_MANAGER_KEY = "MIDWAY_ASYNC_CONTEXT_MANAGER_KEY";
486
+ export declare const DEFAULT_PATTERN: string[];
487
+ export declare const IGNORE_PATTERN: string[];
486
488
  export {};
487
489
  //# 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.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;
3
+ exports.IGNORE_PATTERN = exports.DEFAULT_PATTERN = 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";
@@ -21,4 +21,13 @@ var MidwayProcessTypeEnum;
21
21
  exports.MIDWAY_LOGGER_WRITEABLE_DIR = 'MIDWAY_LOGGER_WRITEABLE_DIR';
22
22
  exports.ASYNC_CONTEXT_KEY = Symbol('ASYNC_CONTEXT_KEY');
23
23
  exports.ASYNC_CONTEXT_MANAGER_KEY = 'MIDWAY_ASYNC_CONTEXT_MANAGER_KEY';
24
+ exports.DEFAULT_PATTERN = [
25
+ '**/**.ts',
26
+ '**/**.js',
27
+ '**/**.mts',
28
+ '**/**.mjs',
29
+ '**/**.cts',
30
+ '**/**.cjs'
31
+ ];
32
+ exports.IGNORE_PATTERN = ['**/**.d.ts', '**/**.d.mts', '**/**.d.cts'];
24
33
  //# sourceMappingURL=interface.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/core",
3
- "version": "3.4.6",
3
+ "version": "3.4.10",
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": "36687482782bcf526efc2a4773c09e166820c1a8"
48
+ "gitHead": "aeb117633ecbc3299002b220f436dc3b5450d361"
49
49
  }