@midwayjs/core 3.12.0-beta.2 → 3.12.1

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2013 - Now midwayjs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -197,6 +197,9 @@ class BaseFramework {
197
197
  ctx.getAttr = (key) => {
198
198
  return ctx.requestContext.getAttr(key);
199
199
  };
200
+ ctx.getApp = () => {
201
+ return this.getApplication();
202
+ };
200
203
  return ctx;
201
204
  },
202
205
  addConfigObject: (obj) => {
@@ -1,34 +1,12 @@
1
- import { ModuleLoadType } from '../interface';
2
- export interface CreateDataSourceInstanceOptions {
3
- /**
4
- * @default false
5
- */
6
- validateConnection?: boolean;
7
- /**
8
- * @default true
9
- */
10
- cacheInstance?: boolean | undefined;
11
- }
12
- interface DataSourceConfig extends CreateDataSourceInstanceOptions {
13
- dataSource: {
14
- entities?: Array<string | unknown>;
15
- [key: string]: unknown;
16
- };
17
- }
18
- export declare abstract class DataSourceManager<T> {
1
+ import { ModuleLoadType, DataSourceManagerConfigOption } from '../interface';
2
+ export declare abstract class DataSourceManager<T, ConnectionOpts extends Record<string, any> = Record<string, any>> {
19
3
  protected dataSource: Map<string, T>;
20
- protected options: Partial<DataSourceConfig>;
4
+ protected options: DataSourceManagerConfigOption<ConnectionOpts>;
21
5
  protected modelMapping: WeakMap<object, any>;
22
6
  private innerDefaultDataSourceName;
23
- protected initDataSource(dataSourceConfig: {
24
- dataSource: {
25
- entities?: Array<string | unknown>;
26
- [key: string]: unknown;
27
- };
28
- cacheInstance?: boolean;
29
- validateConnection?: boolean;
30
- }, appDirOrOptions: {
31
- appDir: string;
7
+ protected initDataSource(dataSourceConfig: DataSourceManagerConfigOption<ConnectionOpts>, baseDirOrOptions: {
8
+ baseDir: string;
9
+ entitiesConfigKey?: string;
32
10
  } | string): Promise<void>;
33
11
  /**
34
12
  * get a data source instance
@@ -46,7 +24,10 @@ export declare abstract class DataSourceManager<T> {
46
24
  * @param dataSourceName
47
25
  */
48
26
  isConnected(dataSourceName: string): Promise<boolean>;
49
- createInstance(config: any, clientName: any, options?: CreateDataSourceInstanceOptions): Promise<T | void>;
27
+ createInstance(config: any, clientName: any, options?: {
28
+ validateConnection?: boolean;
29
+ cacheInstance?: boolean | undefined;
30
+ }): Promise<T | void>;
50
31
  /**
51
32
  * get data source name by model or repository
52
33
  * @param modelOrRepository
@@ -61,5 +42,4 @@ export declare abstract class DataSourceManager<T> {
61
42
  }
62
43
  export declare function formatGlobString(globString: string): string[];
63
44
  export declare function globModels(globString: string, appDir: string, loadMode?: ModuleLoadType): Promise<any[]>;
64
- export {};
65
45
  //# sourceMappingURL=dataSourceManager.d.ts.map
@@ -19,25 +19,27 @@ class DataSourceManager {
19
19
  this.options = {};
20
20
  this.modelMapping = new WeakMap();
21
21
  }
22
- async initDataSource(dataSourceConfig, appDirOrOptions) {
22
+ async initDataSource(dataSourceConfig, baseDirOrOptions) {
23
23
  this.options = dataSourceConfig;
24
24
  if (!this.options.dataSource) {
25
25
  throw new error_1.MidwayParameterError('[DataSourceManager] must set options.dataSource.');
26
26
  }
27
- if (typeof appDirOrOptions === 'string') {
28
- appDirOrOptions = {
29
- appDir: appDirOrOptions,
27
+ if (typeof baseDirOrOptions === 'string') {
28
+ baseDirOrOptions = {
29
+ baseDir: baseDirOrOptions,
30
+ entitiesConfigKey: 'entities',
30
31
  };
31
32
  }
32
33
  for (const dataSourceName in dataSourceConfig.dataSource) {
33
34
  const dataSourceOptions = dataSourceConfig.dataSource[dataSourceName];
34
- if (dataSourceOptions['entities']) {
35
+ const userEntities = dataSourceOptions[baseDirOrOptions.entitiesConfigKey];
36
+ if (userEntities) {
35
37
  const entities = new Set();
36
38
  // loop entities and glob files to model
37
- for (const entity of dataSourceOptions['entities']) {
39
+ for (const entity of userEntities) {
38
40
  if (typeof entity === 'string') {
39
41
  // string will be glob file
40
- const models = await globModels(entity, appDirOrOptions.appDir);
42
+ const models = await globModels(entity, baseDirOrOptions.baseDir);
41
43
  for (const model of models) {
42
44
  entities.add(model);
43
45
  this.modelMapping.set(model, dataSourceName);
@@ -49,8 +51,9 @@ class DataSourceManager {
49
51
  this.modelMapping.set(entity, dataSourceName);
50
52
  }
51
53
  }
52
- dataSourceOptions['entities'] = Array.from(entities);
53
- debug(`[core]: DataManager load ${dataSourceOptions['entities'].length} models from ${dataSourceName}.`);
54
+ dataSourceOptions[baseDirOrOptions.entitiesConfigKey] =
55
+ Array.from(entities);
56
+ debug(`[core]: DataManager load ${dataSourceOptions[baseDirOrOptions.entitiesConfigKey].length} models from ${dataSourceName}.`);
54
57
  }
55
58
  // create data source
56
59
  const opts = {
@@ -41,10 +41,14 @@ export declare const FUNCTION_INJECT_KEY = "midway:function_inject_key";
41
41
  export declare const MIDWAY_LOGGER_WRITEABLE_DIR = "MIDWAY_LOGGER_WRITEABLE_DIR";
42
42
  export declare const REQUEST_CTX_KEY = "ctx";
43
43
  export declare const REQUEST_OBJ_CTX_KEY = "_req_ctx";
44
+ export declare const CONTAINER_OBJ_SCOPE = "_obj_scope";
44
45
  export declare const HTTP_SERVER_KEY = "_midway_http_server";
45
46
  export declare const REQUEST_CTX_LOGGER_CACHE_KEY = "_midway_ctx_logger_cache";
46
47
  export declare const ASYNC_CONTEXT_KEY: unique symbol;
47
48
  export declare const ASYNC_CONTEXT_MANAGER_KEY = "MIDWAY_ASYNC_CONTEXT_MANAGER_KEY";
48
49
  export declare const DEFAULT_PATTERN: string[];
49
50
  export declare const IGNORE_PATTERN: string[];
51
+ export declare const SINGLETON_CONTAINER_CTX: {
52
+ _MAIN_CTX_: boolean;
53
+ };
50
54
  //# sourceMappingURL=constants.d.ts.map
package/dist/constants.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.IGNORE_PATTERN = exports.DEFAULT_PATTERN = exports.ASYNC_CONTEXT_MANAGER_KEY = exports.ASYNC_CONTEXT_KEY = exports.REQUEST_CTX_LOGGER_CACHE_KEY = exports.HTTP_SERVER_KEY = exports.REQUEST_OBJ_CTX_KEY = exports.REQUEST_CTX_KEY = exports.MIDWAY_LOGGER_WRITEABLE_DIR = exports.FUNCTION_INJECT_KEY = exports.KEYS = void 0;
3
+ exports.SINGLETON_CONTAINER_CTX = exports.IGNORE_PATTERN = exports.DEFAULT_PATTERN = exports.ASYNC_CONTEXT_MANAGER_KEY = exports.ASYNC_CONTEXT_KEY = exports.REQUEST_CTX_LOGGER_CACHE_KEY = exports.HTTP_SERVER_KEY = exports.CONTAINER_OBJ_SCOPE = exports.REQUEST_OBJ_CTX_KEY = exports.REQUEST_CTX_KEY = exports.MIDWAY_LOGGER_WRITEABLE_DIR = exports.FUNCTION_INJECT_KEY = exports.KEYS = void 0;
4
4
  /**
5
5
  * 静态参数
6
6
  *
@@ -44,6 +44,7 @@ exports.FUNCTION_INJECT_KEY = 'midway:function_inject_key';
44
44
  exports.MIDWAY_LOGGER_WRITEABLE_DIR = 'MIDWAY_LOGGER_WRITEABLE_DIR';
45
45
  exports.REQUEST_CTX_KEY = 'ctx';
46
46
  exports.REQUEST_OBJ_CTX_KEY = '_req_ctx';
47
+ exports.CONTAINER_OBJ_SCOPE = '_obj_scope';
47
48
  exports.HTTP_SERVER_KEY = '_midway_http_server';
48
49
  exports.REQUEST_CTX_LOGGER_CACHE_KEY = '_midway_ctx_logger_cache';
49
50
  exports.ASYNC_CONTEXT_KEY = Symbol('ASYNC_CONTEXT_KEY');
@@ -57,4 +58,5 @@ exports.DEFAULT_PATTERN = [
57
58
  '**/**.cjs',
58
59
  ];
59
60
  exports.IGNORE_PATTERN = ['**/**.d.ts', '**/**.d.mts', '**/**.d.cts'];
61
+ exports.SINGLETON_CONTAINER_CTX = { _MAIN_CTX_: true };
60
62
  //# sourceMappingURL=constants.js.map
@@ -1,5 +1,5 @@
1
1
  /// <reference types="node" />
2
- import { IFileDetector, IIdentifierRelationShip, IMidwayContainer, IModuleStore, IObjectDefinition, IObjectDefinitionRegistry, ObjectContext, ObjectIdentifier } from '../interface';
2
+ import { IFileDetector, IIdentifierRelationShip, IMidwayContainer, IModuleStore, IObjectDefinition, IObjectDefinitionRegistry, ObjectContext, ObjectIdentifier, ScopeEnum } from '../interface';
3
3
  import { ManagedResolverFactory } from './managedResolverFactory';
4
4
  import * as EventEmitter from 'events';
5
5
  export declare class MidwayContainer implements IMidwayContainer, IModuleStore {
@@ -9,7 +9,9 @@ export declare class MidwayContainer implements IMidwayContainer, IModuleStore {
9
9
  private moduleMap;
10
10
  private _objectCreateEventTarget;
11
11
  parent: IMidwayContainer;
12
- protected ctx: {};
12
+ protected ctx: {
13
+ _MAIN_CTX_: boolean;
14
+ };
13
15
  private fileDetector;
14
16
  private attrMap;
15
17
  private _namespaceSet;
@@ -79,5 +81,6 @@ export declare class MidwayContainer implements IMidwayContainer, IModuleStore {
79
81
  getNamespaceList(): string[];
80
82
  hasDefinition(identifier: ObjectIdentifier): boolean;
81
83
  hasObject(identifier: ObjectIdentifier): boolean;
84
+ getInstanceScope(instance: any): ScopeEnum | undefined;
82
85
  }
83
86
  //# sourceMappingURL=container.d.ts.map
@@ -186,8 +186,8 @@ class MidwayContainer {
186
186
  this._identifierMapping = null;
187
187
  this.moduleMap = null;
188
188
  this.parent = null;
189
- // 仅仅用于兼容requestContainer的ctx
190
- this.ctx = {};
189
+ // 仅仅用于兼容 requestContainer ctx
190
+ this.ctx = constants_1.SINGLETON_CONTAINER_CTX;
191
191
  this.attrMap = new Map();
192
192
  this._namespaceSet = null;
193
193
  this.parent = parent;
@@ -502,6 +502,12 @@ class MidwayContainer {
502
502
  hasObject(identifier) {
503
503
  return this.registry.hasObject(identifier);
504
504
  }
505
+ getInstanceScope(instance) {
506
+ if (instance[constants_1.CONTAINER_OBJ_SCOPE]) {
507
+ return instance[constants_1.CONTAINER_OBJ_SCOPE];
508
+ }
509
+ return undefined;
510
+ }
505
511
  }
506
512
  exports.MidwayContainer = MidwayContainer;
507
513
  //# sourceMappingURL=container.js.map
@@ -1,4 +1,4 @@
1
- import { IManagedResolver, IObjectDefinition, IManagedResolverFactoryCreateOptions, IMidwayContainer, IManagedInstance, InjectModeEnum, ObjectIdentifier } from '../interface';
1
+ import { IManagedInstance, IManagedResolver, IManagedResolverFactoryCreateOptions, IMidwayContainer, InjectModeEnum, IObjectDefinition, ObjectIdentifier } from '../interface';
2
2
  export declare class ManagedReference implements IManagedInstance {
3
3
  type: string;
4
4
  name: string;
@@ -50,5 +50,6 @@ export declare class ManagedResolverFactory {
50
50
  depthFirstSearch(identifier: string, definition: IObjectDefinition, depth?: string[]): boolean;
51
51
  private getObjectEventTarget;
52
52
  private checkSingletonInvokeRequest;
53
+ private setInstanceScope;
53
54
  }
54
55
  //# sourceMappingURL=managedResolverFactory.d.ts.map
@@ -163,12 +163,18 @@ class ManagedResolverFactory {
163
163
  context: this.context,
164
164
  definition,
165
165
  });
166
- if (definition.isSingletonScope() && definition.id) {
167
- this.singletonCache.set(definition.id, inst);
168
- }
169
- // for request scope
170
- if (definition.isRequestScope() && definition.id) {
171
- this.context.registerObject(definition.id, inst);
166
+ if (definition.id) {
167
+ if (definition.isSingletonScope()) {
168
+ this.singletonCache.set(definition.id, inst);
169
+ this.setInstanceScope(inst, interface_1.ScopeEnum.Singleton);
170
+ }
171
+ else if (definition.isRequestScope()) {
172
+ this.context.registerObject(definition.id, inst);
173
+ this.setInstanceScope(inst, interface_1.ScopeEnum.Request);
174
+ }
175
+ else {
176
+ this.setInstanceScope(inst, interface_1.ScopeEnum.Prototype);
177
+ }
172
178
  }
173
179
  this.removeCreateStatus(definition, true);
174
180
  return inst;
@@ -217,6 +223,7 @@ class ManagedResolverFactory {
217
223
  if (definition.isRequestScope() &&
218
224
  definition.constructor.name === 'ObjectDefinition') {
219
225
  debug('id = %s inject ctx', definition.id);
226
+ // set related ctx
220
227
  Object.defineProperty(inst, constants_1.REQUEST_OBJ_CTX_KEY, {
221
228
  value: this.context.get(constants_1.REQUEST_CTX_KEY),
222
229
  writable: false,
@@ -253,14 +260,20 @@ class ManagedResolverFactory {
253
260
  context: this.context,
254
261
  definition,
255
262
  });
256
- if (definition.isSingletonScope() && definition.id) {
257
- debug(`id = ${definition.id}(${definition.name}) set to singleton cache`);
258
- this.singletonCache.set(definition.id, inst);
259
- }
260
- // for request scope
261
- if (definition.isRequestScope() && definition.id) {
262
- debug(`id = ${definition.id}(${definition.name}) set to register object`);
263
- this.context.registerObject(definition.id, inst);
263
+ if (definition.id) {
264
+ if (definition.isSingletonScope()) {
265
+ debug(`id = ${definition.id}(${definition.name}) set to singleton cache`);
266
+ this.singletonCache.set(definition.id, inst);
267
+ this.setInstanceScope(inst, interface_1.ScopeEnum.Singleton);
268
+ }
269
+ else if (definition.isRequestScope()) {
270
+ debug(`id = ${definition.id}(${definition.name}) set to register object`);
271
+ this.context.registerObject(definition.id, inst);
272
+ this.setInstanceScope(inst, interface_1.ScopeEnum.Request);
273
+ }
274
+ else {
275
+ this.setInstanceScope(inst, interface_1.ScopeEnum.Prototype);
276
+ }
264
277
  }
265
278
  this.removeCreateStatus(definition, true);
266
279
  return inst;
@@ -409,6 +422,20 @@ class ManagedResolverFactory {
409
422
  }
410
423
  return true;
411
424
  }
425
+ setInstanceScope(inst, scope) {
426
+ if (typeof inst === 'object') {
427
+ if (scope === interface_1.ScopeEnum.Request &&
428
+ inst[constants_1.REQUEST_OBJ_CTX_KEY] === constants_1.SINGLETON_CONTAINER_CTX) {
429
+ scope = interface_1.ScopeEnum.Singleton;
430
+ }
431
+ Object.defineProperty(inst, constants_1.CONTAINER_OBJ_SCOPE, {
432
+ value: scope,
433
+ writable: false,
434
+ enumerable: false,
435
+ configurable: false,
436
+ });
437
+ }
438
+ }
412
439
  }
413
440
  exports.ManagedResolverFactory = ManagedResolverFactory;
414
441
  //# sourceMappingURL=managedResolverFactory.js.map
@@ -7,6 +7,8 @@ export declare class MidwayRequestContainer extends MidwayContainer {
7
7
  get<T = any>(identifier: any, args?: any): T;
8
8
  getAsync<T = any>(identifier: any, args?: any): Promise<T>;
9
9
  ready(): Promise<void>;
10
- getContext(): {};
10
+ getContext(): {
11
+ _MAIN_CTX_: boolean;
12
+ };
11
13
  }
12
14
  //# sourceMappingURL=requestContainer.d.ts.map
@@ -23,7 +23,7 @@ function ServerlessTrigger(type, metadata = {}) {
23
23
  type,
24
24
  methodName: functionName,
25
25
  metadata,
26
- }, target.constructor);
26
+ }, target);
27
27
  };
28
28
  }
29
29
  exports.ServerlessTrigger = ServerlessTrigger;
package/dist/index.d.ts CHANGED
@@ -17,7 +17,7 @@ export { MidwayDecoratorService } from './service/decoratorService';
17
17
  export { MidwayMockService } from './service/mockService';
18
18
  export { RouterInfo, DynamicRouterInfo, RouterPriority, RouterCollectorOptions, MidwayWebRouterService, } from './service/webRouterService';
19
19
  export { MidwayServerlessFunctionService, WebRouterCollector, } from './service/slsFunctionService';
20
- export { CreateDataSourceInstanceOptions, DataSourceManager, } from './common/dataSourceManager';
20
+ export { DataSourceManager } from './common/dataSourceManager';
21
21
  export * from './service/pipelineService';
22
22
  export * from './common/loggerFactory';
23
23
  export * from './common/serviceFactory';
@@ -368,15 +368,25 @@ export type ServiceFactoryConfigOption<OPTIONS> = {
368
368
  };
369
369
  defaultClientName?: string;
370
370
  };
371
- export type DataSourceManagerConfigOption<OPTIONS> = {
371
+ export type CreateDataSourceInstanceOptions = {
372
+ /**
373
+ * @default false
374
+ */
375
+ validateConnection?: boolean;
376
+ /**
377
+ * @default true
378
+ */
379
+ cacheInstance?: boolean | undefined;
380
+ };
381
+ export type DataSourceManagerConfigOption<OPTIONS, ENTITY_CONFIG_KEY extends string = 'entities'> = {
372
382
  default?: PowerPartial<OPTIONS>;
373
383
  defaultDataSourceName?: string;
374
384
  dataSource?: {
375
385
  [key: string]: PowerPartial<{
376
- entities: any[];
386
+ [keyName in ENTITY_CONFIG_KEY]: any[];
377
387
  } & OPTIONS>;
378
388
  };
379
- };
389
+ } & CreateDataSourceInstanceOptions;
380
390
  type ConfigType<T> = T extends (...args: any[]) => any ? Writable<PowerPartial<ReturnType<T>>> : Writable<PowerPartial<T>>;
381
391
  /**
382
392
  * Get definition from config
@@ -593,6 +603,11 @@ export interface IMidwayContainer extends IObjectFactory, WithFn<IObjectLifeCycl
593
603
  * @param key
594
604
  */
595
605
  getAttr<T>(key: string): T;
606
+ /**
607
+ * Get instance IoC container scope
608
+ * @param instance
609
+ */
610
+ getInstanceScope(instance: any): ScopeEnum | undefined;
596
611
  }
597
612
  /**
598
613
  * @deprecated
@@ -645,6 +660,10 @@ export interface Context {
645
660
  * @param key
646
661
  */
647
662
  getAttr<T>(key: string): T;
663
+ /**
664
+ * Get current related application instance.
665
+ */
666
+ getApp(): IMidwayApplication;
648
667
  }
649
668
  export type IMidwayContext<FrameworkContext = unknown> = Context & FrameworkContext;
650
669
  export type NextFunction = () => Promise<any>;
@@ -3,10 +3,8 @@
3
3
  /// <reference types="node" />
4
4
  import http = require('http');
5
5
  import https = require('https');
6
- type MethodType = 'GET' | 'POST';
7
6
  type MimeType = 'text' | 'json' | undefined;
8
7
  interface IOptions extends https.RequestOptions {
9
- method?: MethodType;
10
8
  headers?: any;
11
9
  contentType?: MimeType;
12
10
  dataType?: MimeType;
@@ -54,6 +54,7 @@ const safeRequire = (p, enabledCache = true) => {
54
54
  }
55
55
  };
56
56
  exports.safeRequire = safeRequire;
57
+ const innerLoadModuleCache = {};
57
58
  /**
58
59
  * load module, and it can be chosen commonjs or esm mode
59
60
  * @param p
@@ -76,9 +77,18 @@ const loadModule = async (p, options = {}) => {
76
77
  else {
77
78
  // if json file, import need add options
78
79
  if (p.endsWith('.json')) {
79
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
80
- // @ts-ignore
81
- return (await import(p, { assert: { type: 'json' } })).default;
80
+ /**
81
+ * attention: import json not support under nodejs 16
82
+ * use readFileSync instead
83
+ */
84
+ if (!innerLoadModuleCache[p]) {
85
+ // return (await import(p, { assert: { type: 'json' } })).default;
86
+ const content = (0, fs_1.readFileSync)(p, {
87
+ encoding: 'utf-8',
88
+ });
89
+ innerLoadModuleCache[p] = JSON.parse(content);
90
+ }
91
+ return innerLoadModuleCache[p];
82
92
  }
83
93
  else {
84
94
  return await import(p);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/core",
3
- "version": "3.12.0-beta.2",
3
+ "version": "3.12.1",
4
4
  "description": "midway core",
5
5
  "main": "dist/index",
6
6
  "typings": "dist/index.d.ts",
@@ -42,5 +42,5 @@
42
42
  "engines": {
43
43
  "node": ">=12"
44
44
  },
45
- "gitHead": "a603d2348d6141f8f723901498f03a162a037708"
45
+ "gitHead": "48413b87b12354cb8207de6aa58e0a4ca22ea000"
46
46
  }