@midwayjs/core 3.11.0 → 3.11.4

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,9 +1,34 @@
1
+ export interface CreateDataSourceInstanceOptions {
2
+ /**
3
+ * @default false
4
+ */
5
+ validateConnection?: boolean;
6
+ /**
7
+ * @default true
8
+ */
9
+ cacheInstance?: boolean | undefined;
10
+ }
11
+ interface DataSourceConfig extends CreateDataSourceInstanceOptions {
12
+ dataSource: {
13
+ entities?: Array<string | unknown>;
14
+ [key: string]: unknown;
15
+ };
16
+ }
1
17
  export declare abstract class DataSourceManager<T> {
2
18
  protected dataSource: Map<string, T>;
3
- protected options: {};
19
+ protected options: Partial<DataSourceConfig>;
4
20
  protected modelMapping: WeakMap<object, any>;
5
21
  private innerDefaultDataSourceName;
6
- protected initDataSource(options: any, appDir: string): Promise<void>;
22
+ protected initDataSource(dataSourceConfig: {
23
+ dataSource: {
24
+ entities?: Array<string | unknown>;
25
+ [key: string]: unknown;
26
+ };
27
+ cacheInstance?: boolean;
28
+ validateConnection?: boolean;
29
+ }, appDirOrOptions: {
30
+ appDir: string;
31
+ } | string): Promise<void>;
7
32
  /**
8
33
  * get a data source instance
9
34
  * @param dataSourceName
@@ -35,14 +60,5 @@ export declare abstract class DataSourceManager<T> {
35
60
  }
36
61
  export declare function formatGlobString(globString: string): string[];
37
62
  export declare function globModels(globString: string, appDir: string): any[];
38
- export interface CreateDataSourceInstanceOptions {
39
- /**
40
- * @default false
41
- */
42
- validateConnection?: boolean;
43
- /**
44
- * @default true
45
- */
46
- cacheInstance?: boolean | undefined;
47
- }
63
+ export {};
48
64
  //# sourceMappingURL=dataSourceManager.d.ts.map
@@ -10,43 +10,51 @@ const glob_1 = require("@midwayjs/glob");
10
10
  const path_1 = require("path");
11
11
  const types_1 = require("../util/types");
12
12
  const constants_1 = require("../constants");
13
+ const util_1 = require("util");
14
+ const debug = (0, util_1.debuglog)('midway:debug');
13
15
  class DataSourceManager {
14
16
  constructor() {
15
17
  this.dataSource = new Map();
16
18
  this.options = {};
17
19
  this.modelMapping = new WeakMap();
18
20
  }
19
- async initDataSource(options, appDir) {
20
- this.options = options;
21
- if (!options.dataSource) {
21
+ async initDataSource(dataSourceConfig, appDirOrOptions) {
22
+ this.options = dataSourceConfig;
23
+ if (!this.options.dataSource) {
22
24
  throw new error_1.MidwayParameterError('[DataSourceManager] must set options.dataSource.');
23
25
  }
24
- for (const dataSourceName in options.dataSource) {
25
- const dataSourceOptions = options.dataSource[dataSourceName];
26
+ if (typeof appDirOrOptions === 'string') {
27
+ appDirOrOptions = {
28
+ appDir: appDirOrOptions,
29
+ };
30
+ }
31
+ for (const dataSourceName in dataSourceConfig.dataSource) {
32
+ const dataSourceOptions = dataSourceConfig.dataSource[dataSourceName];
26
33
  if (dataSourceOptions['entities']) {
27
34
  const entities = new Set();
28
35
  // loop entities and glob files to model
29
36
  for (const entity of dataSourceOptions['entities']) {
30
37
  if (typeof entity === 'string') {
31
38
  // string will be glob file
32
- const models = globModels(entity, appDir);
39
+ const models = globModels(entity, appDirOrOptions.appDir);
33
40
  for (const model of models) {
34
41
  entities.add(model);
35
42
  this.modelMapping.set(model, dataSourceName);
36
43
  }
37
44
  }
38
45
  else {
39
- // model will be add to array
46
+ // model will be added to array
40
47
  entities.add(entity);
41
48
  this.modelMapping.set(entity, dataSourceName);
42
49
  }
43
50
  }
44
51
  dataSourceOptions['entities'] = Array.from(entities);
52
+ debug(`[core]: DataManager load ${dataSourceOptions['entities'].length} models from ${dataSourceName}.`);
45
53
  }
46
54
  // create data source
47
55
  const opts = {
48
- cacheInstance: options.cacheInstance,
49
- validateConnection: options.validateConnection,
56
+ cacheInstance: dataSourceConfig.cacheInstance,
57
+ validateConnection: dataSourceConfig.validateConnection,
50
58
  };
51
59
  await this.createInstance(dataSourceOptions, dataSourceName, opts);
52
60
  }
@@ -7,6 +7,7 @@ const constant_1 = require("./constant");
7
7
  const types_1 = require("../util/types");
8
8
  const camelCase_1 = require("../util/camelCase");
9
9
  const util_1 = require("../util");
10
+ const pathFileUtil_1 = require("../util/pathFileUtil");
10
11
  const debug = require('util').debuglog('midway:core');
11
12
  exports.PRELOAD_MODULE_KEY = 'INJECTION_PRELOAD_MODULE_KEY';
12
13
  exports.INJECT_CLASS_KEY_PREFIX = 'INJECTION_CLASS_META_DATA';
@@ -249,6 +250,13 @@ let manager = new DecoratorManager();
249
250
  if (typeof global === 'object') {
250
251
  if (global['MIDWAY_GLOBAL_DECORATOR_MANAGER']) {
251
252
  console.warn('DecoratorManager not singleton and please check @midwayjs/core version by "npm ls @midwayjs/core"');
253
+ const coreModulePathList = (0, pathFileUtil_1.getModuleRequirePathList)('@midwayjs/core');
254
+ if (coreModulePathList.length) {
255
+ console.info('The module may be located in:');
256
+ coreModulePathList.forEach((path, index) => {
257
+ console.info(`${index + 1}. ${path}`);
258
+ });
259
+ }
252
260
  manager = global['MIDWAY_GLOBAL_DECORATOR_MANAGER'];
253
261
  }
254
262
  else {
@@ -1,4 +1,4 @@
1
- import { IMidwayContext, PipeUnionTransform } from '../../interface';
1
+ import { IMidwayContext, ParamDecoratorOptions, PipeUnionTransform } from '../../interface';
2
2
  export declare enum RouteParamTypes {
3
3
  QUERY = "query",
4
4
  BODY = "body",
@@ -22,7 +22,7 @@ export interface RouterParamValue {
22
22
  export declare type KoaLikeCustomParamDecorator<T = unknown> = (ctx: IMidwayContext) => T | Promise<T>;
23
23
  export declare type ExpressLikeCustomParamDecorator<T = unknown> = (req: any, res: any) => T | Promise<T>;
24
24
  export declare type CustomParamDecorator<T = unknown> = KoaLikeCustomParamDecorator<T> | ExpressLikeCustomParamDecorator<T>;
25
- export declare const createRequestParamDecorator: (transform: CustomParamDecorator, pipes?: Array<PipeUnionTransform>) => ParameterDecorator;
25
+ export declare const createRequestParamDecorator: (transform: CustomParamDecorator, pipesOrOptions?: ParamDecoratorOptions | Array<PipeUnionTransform>) => ParameterDecorator;
26
26
  export declare const Session: (propertyOrPipes?: string | PipeUnionTransform[], pipes?: PipeUnionTransform[]) => ParameterDecorator;
27
27
  export declare const Body: (propertyOrPipes?: string | PipeUnionTransform[], pipes?: PipeUnionTransform[]) => ParameterDecorator;
28
28
  export declare const Query: (propertyOrPipes?: string | PipeUnionTransform[], pipes?: PipeUnionTransform[]) => ParameterDecorator;
@@ -33,8 +33,14 @@ const createParamMapping = function (type) {
33
33
  });
34
34
  };
35
35
  };
36
- const createRequestParamDecorator = function (transform, pipes) {
37
- return createParamMapping(RouteParamTypes.CUSTOM)(transform, pipes);
36
+ const createRequestParamDecorator = function (transform, pipesOrOptions) {
37
+ pipesOrOptions = pipesOrOptions || {};
38
+ if (Array.isArray(pipesOrOptions)) {
39
+ pipesOrOptions = {
40
+ pipes: pipesOrOptions,
41
+ };
42
+ }
43
+ return createParamMapping(RouteParamTypes.CUSTOM)(transform, pipesOrOptions.pipes);
38
44
  };
39
45
  exports.createRequestParamDecorator = createRequestParamDecorator;
40
46
  const Session = (propertyOrPipes, pipes) => createParamMapping(RouteParamTypes.SESSION)(propertyOrPipes, pipes);
@@ -3,6 +3,43 @@ import type { LoggerOptions, LoggerContextFormat } from '@midwayjs/logger';
3
3
  import * as EventEmitter from 'events';
4
4
  import type { AsyncContextManager } from './common/asyncContextManager';
5
5
  import type { LoggerFactory } from './common/loggerFactory';
6
+ export type PowerPartial<T> = {
7
+ [U in keyof T]?: T[U] extends {} ? PowerPartial<T[U]> : T[U];
8
+ };
9
+ /**
10
+ * Make object property writeable
11
+ */
12
+ export type Writable<T> = {
13
+ -readonly [P in keyof T]: T[P];
14
+ };
15
+ /**
16
+ * Utility type that adds a `fn` parameter to each method in the input type `T`,
17
+ * transforming the original method's parameter types and return type into a function type.
18
+ *
19
+ * @example
20
+ * // Input:
21
+ * interface MyInterface {
22
+ * method1(a: string, b: number): boolean;
23
+ * method2(x: Foo, y: Bar): void;
24
+ * }
25
+ *
26
+ * // Output:
27
+ * interface MyInterfaceWithFn {
28
+ * method1(fn: (a: string, b: number) => boolean): void;
29
+ * method2(fn: (x: Foo, y: Bar) => void): void;
30
+ * }
31
+ */
32
+ export type WithFn<T> = {
33
+ [K in keyof T]: T[K] extends (...args: infer P) => infer R ? (fn: (...args: P) => R) => void : T[K];
34
+ };
35
+ /**
36
+ * Transform an object type `T` with methods that have function-type parameters
37
+ * to a new object type with the same methods, but with the parameters
38
+ * extracted as separate properties.
39
+ */
40
+ export type WithoutFn<T> = {
41
+ [K in keyof T]: T[K] extends (arg: any, ...args: any[]) => any ? (...args: Parameters<T[K]>) => ReturnType<T[K]> : T[K];
42
+ };
6
43
  export type MiddlewareParamArray = Array<string | any>;
7
44
  export type ObjectIdentifier = string | Symbol;
8
45
  export type GroupModeType = 'one' | 'multi';
@@ -243,6 +280,7 @@ export interface JoinPoint {
243
280
  target: any;
244
281
  args: any[];
245
282
  proceed?(...args: any[]): any;
283
+ proceedIsAsyncFunction?: boolean;
246
284
  }
247
285
  export interface AspectMetadata {
248
286
  aspectTarget: any;
@@ -322,9 +360,6 @@ export interface MidwayCoreDefaultConfig {
322
360
  enable: boolean;
323
361
  };
324
362
  }
325
- export type PowerPartial<T> = {
326
- [U in keyof T]?: T[U] extends {} ? PowerPartial<T[U]> : T[U];
327
- };
328
363
  export type ServiceFactoryConfigOption<OPTIONS> = {
329
364
  default?: PowerPartial<OPTIONS>;
330
365
  client?: PowerPartial<OPTIONS>;
@@ -347,12 +382,6 @@ type ConfigType<T> = T extends (...args: any[]) => any ? Writable<PowerPartial<R
347
382
  * Get definition from config
348
383
  */
349
384
  export type FileConfigOption<T, K = unknown> = K extends keyof ConfigType<T> ? Pick<ConfigType<T>, K> : ConfigType<T>;
350
- /**
351
- * Make object property writeable
352
- */
353
- export type Writable<T> = {
354
- -readonly [P in keyof T]: T[P];
355
- };
356
385
  /**
357
386
  * Lifecycle Definition
358
387
  * 生命周期定义
@@ -406,11 +435,11 @@ export interface ObjectBeforeDestroyOptions extends ObjectLifeCycleOptions {
406
435
  * 对象生命周期
407
436
  */
408
437
  export interface IObjectLifeCycle {
409
- onBeforeBind(fn: (Clzz: any, options: ObjectBeforeBindOptions) => void): any;
410
- onBeforeObjectCreated(fn: (Clzz: any, options: ObjectBeforeCreatedOptions) => void): any;
411
- onObjectCreated<T>(fn: (ins: T, options: ObjectCreatedOptions<T>) => void): any;
412
- onObjectInit<T>(fn: (ins: T, options: ObjectInitOptions) => void): any;
413
- onBeforeObjectDestroy<T>(fn: (ins: T, options: ObjectBeforeDestroyOptions) => void): any;
438
+ onBeforeBind(Clzz: any, options: ObjectBeforeBindOptions): void;
439
+ onBeforeObjectCreated(Clzz: any, options: ObjectBeforeCreatedOptions): void;
440
+ onObjectCreated<T>(ins: T, options: ObjectCreatedOptions<T>): void;
441
+ onObjectInit<T>(ins: T, options: ObjectInitOptions): void;
442
+ onBeforeObjectDestroy<T>(ins: T, options: ObjectBeforeDestroyOptions): void;
414
443
  }
415
444
  /**
416
445
  * Object Definition
@@ -536,7 +565,7 @@ export interface IIdentifierRelationShip {
536
565
  hasRelation(id: ObjectIdentifier): boolean;
537
566
  getRelation(id: ObjectIdentifier): string;
538
567
  }
539
- export interface IMidwayContainer extends IObjectFactory, IObjectLifeCycle {
568
+ export interface IMidwayContainer extends IObjectFactory, WithFn<IObjectLifeCycle> {
540
569
  parent: IMidwayContainer;
541
570
  identifierMapping: IIdentifierRelationShip;
542
571
  objectCreateEventTarget: EventEmitter;
@@ -78,6 +78,7 @@ let MidwayAspectService = class MidwayAspectService {
78
78
  target: this,
79
79
  args: args,
80
80
  proceed: newProceed,
81
+ proceedIsAsyncFunction: true,
81
82
  };
82
83
  if (typeof aspectObject === 'function') {
83
84
  aspectObject = aspectObject();
@@ -122,6 +123,7 @@ let MidwayAspectService = class MidwayAspectService {
122
123
  target: this,
123
124
  args: args,
124
125
  proceed: newProceed,
126
+ proceedIsAsyncFunction: false,
125
127
  };
126
128
  if (typeof aspectObject === 'function') {
127
129
  aspectObject = aspectObject();
@@ -15,6 +15,8 @@ const interface_1 = require("../interface");
15
15
  const error_1 = require("../error");
16
16
  const util_1 = require("../util");
17
17
  const types_1 = require("../util/types");
18
+ const util_2 = require("util");
19
+ const debug = (0, util_2.debuglog)('midway:debug');
18
20
  let MidwayMiddlewareService = class MidwayMiddlewareService {
19
21
  constructor(applicationContext) {
20
22
  this.applicationContext = applicationContext;
@@ -89,6 +91,9 @@ let MidwayMiddlewareService = class MidwayMiddlewareService {
89
91
  fn = next;
90
92
  if (!fn)
91
93
  return Promise.resolve();
94
+ const middlewareName = `${name ? `${name}.` : ''}${index} ${fn._name || fn.name || 'anonymous'}`;
95
+ const startTime = Date.now();
96
+ debug(`[middleware]: in ${middlewareName} +0`);
92
97
  try {
93
98
  if (supportBody) {
94
99
  return Promise.resolve(fn(context, dispatch.bind(null, i + 1), {
@@ -105,16 +110,21 @@ let MidwayMiddlewareService = class MidwayMiddlewareService {
105
110
  else if (context['body'] !== undefined) {
106
111
  result = context['body'];
107
112
  }
113
+ debug(`[middleware]: out ${middlewareName} +${Date.now() - startTime} with body`);
108
114
  return result;
109
115
  });
110
116
  }
111
117
  else {
112
118
  return Promise.resolve(fn(context, dispatch.bind(null, i + 1), {
113
119
  index,
114
- }));
120
+ })).then(result => {
121
+ debug(`[middleware]: out ${middlewareName} +${Date.now() - startTime}`);
122
+ return result;
123
+ });
115
124
  }
116
125
  }
117
126
  catch (err) {
127
+ debug(`[middleware]: out ${middlewareName} +${Date.now() - startTime} with err ${err.message}`);
118
128
  return Promise.reject(err);
119
129
  }
120
130
  }
@@ -18,6 +18,7 @@ export declare const getCurrentEnvironment: () => string;
18
18
  */
19
19
  export declare const safeRequire: (p: any, enabledCache?: boolean) => any;
20
20
  /**
21
+ * @example
21
22
  * safelyGet(['a','b'],{a: {b: 2}}) // => 2
22
23
  * safelyGet(['a','b'],{c: {b: 2}}) // => undefined
23
24
  * safelyGet(['a','1'],{a: {"1": 2}}) // => 2
@@ -55,6 +55,7 @@ const safeRequire = (p, enabledCache = true) => {
55
55
  };
56
56
  exports.safeRequire = safeRequire;
57
57
  /**
58
+ * @example
58
59
  * safelyGet(['a','b'],{a: {b: 2}}) // => 2
59
60
  * safelyGet(['a','b'],{c: {b: 2}}) // => undefined
60
61
  * safelyGet(['a','1'],{a: {"1": 2}}) // => 2
@@ -7,4 +7,5 @@ export declare const PathFileUtil: {
7
7
  isPathEqual: typeof isPathEqual;
8
8
  getFileContentSync: typeof getFileContentSync;
9
9
  };
10
+ export declare function getModuleRequirePathList(moduleName: string): string[];
10
11
  //# sourceMappingURL=pathFileUtil.d.ts.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PathFileUtil = exports.getFileContentSync = exports.isPathEqual = exports.isPath = void 0;
3
+ exports.getModuleRequirePathList = exports.PathFileUtil = exports.getFileContentSync = exports.isPathEqual = exports.isPath = void 0;
4
4
  const path_1 = require("path");
5
5
  const fs_1 = require("fs");
6
6
  function isPath(p) {
@@ -32,4 +32,31 @@ exports.PathFileUtil = {
32
32
  isPathEqual,
33
33
  getFileContentSync,
34
34
  };
35
+ function getModuleRequirePathList(moduleName) {
36
+ const moduleNameList = [moduleName, moduleName.replace(/\//g, '_')];
37
+ let moduleNameMap = {};
38
+ const modulePathList = [];
39
+ Object.keys(require.cache || {}).forEach(moduleName => {
40
+ let moduleIndex = -1;
41
+ for (const moduleName of moduleNameList) {
42
+ const index = moduleName.indexOf(moduleName);
43
+ if (index !== -1) {
44
+ moduleIndex = index;
45
+ break;
46
+ }
47
+ }
48
+ if (moduleIndex === -1) {
49
+ return;
50
+ }
51
+ const modulePath = moduleName.slice(0, moduleIndex);
52
+ if (moduleNameMap[modulePath]) {
53
+ return;
54
+ }
55
+ moduleNameMap[modulePath] = true;
56
+ modulePathList.push(modulePath);
57
+ });
58
+ moduleNameMap = undefined;
59
+ return modulePathList;
60
+ }
61
+ exports.getModuleRequirePathList = getModuleRequirePathList;
35
62
  //# sourceMappingURL=pathFileUtil.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/core",
3
- "version": "3.11.0",
3
+ "version": "3.11.4",
4
4
  "description": "midway core",
5
5
  "main": "dist/index",
6
6
  "typings": "dist/index.d.ts",
@@ -23,7 +23,7 @@
23
23
  "license": "MIT",
24
24
  "devDependencies": {
25
25
  "koa": "2.14.1",
26
- "mm": "3.2.1",
26
+ "mm": "3.2.2",
27
27
  "raw-body": "2.5.2",
28
28
  "sinon": "15.0.3"
29
29
  },
@@ -42,5 +42,5 @@
42
42
  "engines": {
43
43
  "node": ">=12"
44
44
  },
45
- "gitHead": "eadb977e7fddcd4287c099fc32b601cd51702514"
45
+ "gitHead": "43dab73370ef7f9bf7778513ea4090a977b1f786"
46
46
  }