@midwayjs/core 3.7.0 → 3.9.0

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.
@@ -77,9 +77,9 @@ export declare abstract class BaseFramework<APP extends IMidwayApplication<CTX>,
77
77
  */
78
78
  protected afterContainerReady(options: Partial<IMidwayBootstrapOptions>): Promise<void>;
79
79
  applyMiddleware<R, N>(lastMiddleware?: CommonMiddlewareUnion<CTX, R, N>): Promise<MiddlewareRespond<CTX, R, N>>;
80
- getLogger(name?: string): ILogger;
80
+ getLogger(name?: string): any;
81
81
  getCoreLogger(): ILogger;
82
- createLogger(name: string, option?: LoggerOptions): ILogger;
82
+ createLogger(name: string, option?: LoggerOptions): any;
83
83
  getProjectName(): string;
84
84
  getFrameworkName(): string;
85
85
  useMiddleware(middleware: CommonMiddlewareUnion<CTX, ResOrNext, Next>): void;
@@ -2,6 +2,7 @@ export declare abstract class DataSourceManager<T> {
2
2
  protected dataSource: Map<string, T>;
3
3
  protected options: {};
4
4
  protected modelMapping: WeakMap<object, any>;
5
+ private innerDefaultDataSourceName;
5
6
  protected initDataSource(options: any, appDir: string): Promise<void>;
6
7
  /**
7
8
  * get a data source instance
@@ -32,6 +33,7 @@ export declare abstract class DataSourceManager<T> {
32
33
  stop(): Promise<void>;
33
34
  getDefaultDataSourceName(): string;
34
35
  }
36
+ export declare function formatGlobString(globString: string): string[];
35
37
  export declare function globModels(globString: string, appDir: string): any[];
36
38
  export interface CreateDataSourceInstanceOptions {
37
39
  /**
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.globModels = exports.DataSourceManager = void 0;
3
+ exports.globModels = exports.formatGlobString = exports.DataSourceManager = void 0;
4
4
  /**
5
5
  * 数据源管理器实现
6
6
  */
@@ -113,30 +113,44 @@ class DataSourceManager {
113
113
  this.dataSource.clear();
114
114
  }
115
115
  getDefaultDataSourceName() {
116
- return this.options['defaultDataSourceName'];
116
+ if (this.innerDefaultDataSourceName === undefined) {
117
+ if (this.options['defaultDataSourceName']) {
118
+ this.innerDefaultDataSourceName = this.options['defaultDataSourceName'];
119
+ }
120
+ else if (this.dataSource.size === 1) {
121
+ // Set the default source name when there is only one data source
122
+ this.innerDefaultDataSourceName = Array.from(this.dataSource.keys())[0];
123
+ }
124
+ else {
125
+ // Set empty string for cache
126
+ this.innerDefaultDataSourceName = '';
127
+ }
128
+ }
129
+ return this.innerDefaultDataSourceName;
117
130
  }
118
131
  }
119
132
  exports.DataSourceManager = DataSourceManager;
120
- function globModels(globString, appDir) {
121
- let cwd;
133
+ function formatGlobString(globString) {
122
134
  let pattern;
123
- if (globString.endsWith('**')) {
124
- // 去掉尾部的 **,因为 glob 会自动添加
125
- globString = globString.slice(0, -2);
135
+ if (!/^\*/.test(globString)) {
136
+ globString = '/' + globString;
126
137
  }
127
- if (/\*/.test(globString)) {
128
- cwd = appDir;
129
- pattern = [...constants_1.DEFAULT_PATTERN.map(p => (0, path_1.join)(globString, p))];
130
- pattern.push(globString);
138
+ const parsePattern = (0, path_1.parse)(globString);
139
+ if (parsePattern.base && (/\*/.test(parsePattern.base) || parsePattern.ext)) {
140
+ pattern = [globString];
131
141
  }
132
142
  else {
133
- pattern = [...constants_1.DEFAULT_PATTERN];
134
- cwd = (0, path_1.join)(appDir, globString);
143
+ pattern = [...constants_1.DEFAULT_PATTERN.map(p => (0, path_1.join)(globString, p))];
135
144
  }
145
+ return pattern;
146
+ }
147
+ exports.formatGlobString = formatGlobString;
148
+ function globModels(globString, appDir) {
149
+ const pattern = formatGlobString(globString);
136
150
  const models = [];
137
151
  // string will be glob file
138
152
  const files = (0, glob_1.run)(pattern, {
139
- cwd,
153
+ cwd: appDir,
140
154
  ignore: constants_1.IGNORE_PATTERN,
141
155
  });
142
156
  for (const file of files) {
@@ -0,0 +1,8 @@
1
+ import { ILogger } from '../interface';
2
+ export declare abstract class LoggerFactory<Logger extends ILogger, LoggerOptions> {
3
+ abstract createLogger(name: string, options: LoggerOptions): Logger;
4
+ abstract getLogger(loggerName: string): Logger;
5
+ abstract close(loggerName?: string): any;
6
+ abstract removeLogger(loggerName: string): any;
7
+ }
8
+ //# sourceMappingURL=loggerFactory.d.ts.map
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LoggerFactory = void 0;
4
+ class LoggerFactory {
5
+ }
6
+ exports.LoggerFactory = LoggerFactory;
7
+ //# sourceMappingURL=loggerFactory.js.map
@@ -1,16 +1,18 @@
1
+ import { IServiceFactory } from '../interface';
1
2
  /**
2
3
  * 多客户端工厂实现
3
4
  */
4
- export declare abstract class ServiceFactory<T> {
5
+ export declare abstract class ServiceFactory<T> implements IServiceFactory<T> {
5
6
  protected clients: Map<string, T>;
6
7
  protected options: {};
7
8
  protected initClients(options?: any): Promise<void>;
8
9
  get<U = T>(id?: string): U;
9
10
  has(id: string): boolean;
10
- createInstance(config: any, clientName?: any): Promise<T | void>;
11
+ createInstance(config: any, clientName?: any): Promise<T | undefined>;
11
12
  abstract getName(): string;
12
13
  protected abstract createClient(config: any, clientName: any): Promise<T | void> | (T | void);
13
14
  protected destroyClient(client: T): Promise<void>;
14
15
  stop(): Promise<void>;
16
+ getDefaultClientName(): string;
15
17
  }
16
18
  //# sourceMappingURL=serviceFactory.d.ts.map
@@ -17,7 +17,6 @@ class ServiceFactory {
17
17
  options.clients = options.clients || {};
18
18
  options.clients['default'] = options.clients['default'] || {};
19
19
  (0, extend_1.extend)(true, options.clients['default'], options.client);
20
- delete options.client;
21
20
  }
22
21
  // multi client
23
22
  if (options.clients) {
@@ -49,6 +48,9 @@ class ServiceFactory {
49
48
  await this.destroyClient(value);
50
49
  }
51
50
  }
51
+ getDefaultClientName() {
52
+ return this.options['defaultClientName'];
53
+ }
52
54
  }
53
55
  exports.ServiceFactory = ServiceFactory;
54
56
  //# sourceMappingURL=serviceFactory.js.map
@@ -14,7 +14,7 @@ export declare const KEYS: {
14
14
  PROPS_ELEMENT: string;
15
15
  PROP_ELEMENT: string;
16
16
  SET_ELEMENT: string;
17
- CONSTRUCTORARG_ELEMENT: string;
17
+ CONSTRUCTOR_ARG_ELEMENT: string;
18
18
  REF_ELEMENT: string;
19
19
  JSON_ELEMENT: string;
20
20
  CONFIGURATION_ELEMENT: string;
@@ -37,16 +37,6 @@ export declare const KEYS: {
37
37
  EXPRESSION_ATTRIBUTE: string;
38
38
  EXECUTE_ATTRIBUTE: string;
39
39
  };
40
- export declare const VALUE_TYPE: {
41
- STRING: string;
42
- DATE: string;
43
- NUMBER: string;
44
- INTEGER: string;
45
- TEMPLATE: string;
46
- MANAGED: string;
47
- OBJECT: string;
48
- BOOLEAN: string;
49
- };
50
40
  export declare const FUNCTION_INJECT_KEY = "midway:function_inject_key";
51
41
  export declare const MIDWAY_LOGGER_WRITEABLE_DIR = "MIDWAY_LOGGER_WRITEABLE_DIR";
52
42
  export declare const REQUEST_CTX_KEY = "ctx";
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.VALUE_TYPE = exports.KEYS = void 0;
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;
4
4
  /**
5
5
  * 静态参数
6
6
  *
@@ -17,7 +17,7 @@ exports.KEYS = {
17
17
  PROPS_ELEMENT: 'props',
18
18
  PROP_ELEMENT: 'prop',
19
19
  SET_ELEMENT: 'set',
20
- CONSTRUCTORARG_ELEMENT: 'constructor-arg',
20
+ CONSTRUCTOR_ARG_ELEMENT: 'constructor-arg',
21
21
  REF_ELEMENT: 'ref',
22
22
  JSON_ELEMENT: 'json',
23
23
  CONFIGURATION_ELEMENT: 'configuration',
@@ -40,16 +40,6 @@ exports.KEYS = {
40
40
  EXPRESSION_ATTRIBUTE: 'expression',
41
41
  EXECUTE_ATTRIBUTE: 'execute',
42
42
  };
43
- exports.VALUE_TYPE = {
44
- STRING: 'string',
45
- DATE: 'date',
46
- NUMBER: 'number',
47
- INTEGER: 'int',
48
- TEMPLATE: 'template',
49
- MANAGED: 'managed',
50
- OBJECT: 'object',
51
- BOOLEAN: 'boolean',
52
- };
53
43
  exports.FUNCTION_INJECT_KEY = 'midway:function_inject_key';
54
44
  exports.MIDWAY_LOGGER_WRITEABLE_DIR = 'MIDWAY_LOGGER_WRITEABLE_DIR';
55
45
  exports.REQUEST_CTX_KEY = 'ctx';
@@ -1,3 +1,5 @@
1
1
  import { ObjectIdentifier } from '../interface';
2
+ import { IServiceFactory } from '../../interface';
2
3
  export declare function Inject(identifier?: ObjectIdentifier): (target: any, targetKey: string) => void;
4
+ export declare function InjectClient(serviceFactoryClz: new (...args: any[]) => IServiceFactory<unknown>, clientName?: string): PropertyDecorator;
3
5
  //# sourceMappingURL=inject.d.ts.map
@@ -1,11 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Inject = void 0;
3
+ exports.InjectClient = exports.Inject = void 0;
4
4
  const decoratorManager_1 = require("../decoratorManager");
5
+ const constant_1 = require("../constant");
5
6
  function Inject(identifier) {
6
7
  return function (target, targetKey) {
7
8
  (0, decoratorManager_1.savePropertyInject)({ target, targetKey, identifier });
8
9
  };
9
10
  }
10
11
  exports.Inject = Inject;
12
+ function InjectClient(serviceFactoryClz, clientName) {
13
+ return (0, decoratorManager_1.createCustomPropertyDecorator)(constant_1.FACTORY_SERVICE_CLIENT_KEY, {
14
+ serviceFactoryClz,
15
+ clientName,
16
+ });
17
+ }
18
+ exports.InjectClient = InjectClient;
11
19
  //# sourceMappingURL=inject.js.map
@@ -6,6 +6,7 @@ export declare const ASPECT_KEY = "common:aspect";
6
6
  export declare const CATCH_KEY = "common:catch";
7
7
  export declare const MATCH_KEY = "common:match";
8
8
  export declare const GUARD_KEY = "common:guard";
9
+ export declare const FACTORY_SERVICE_CLIENT_KEY = "common:service_factory:client";
9
10
  export declare const FUNC_KEY = "faas:func";
10
11
  export declare const SERVERLESS_FUNC_KEY = "faas:serverless:function";
11
12
  export declare const CONTROLLER_KEY = "web:controller";
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OBJ_DEF_CLS = exports.TAGGED_FUN = exports.TAGGED_CLS = exports.INJECT_CUSTOM_PARAM = exports.INJECT_CUSTOM_METHOD = exports.INJECT_CUSTOM_PROPERTY = exports.INJECT_TAG = exports.NAMED_TAG = exports.CLASS_KEY_CONSTRUCTOR = exports.APPLICATION_CONTEXT_KEY = exports.APPLICATION_KEY = exports.LOGGER_KEY = exports.PLUGIN_KEY = exports.CONFIG_KEY = exports.MS_HSF_METHOD_KEY = exports.MS_DUBBO_METHOD_KEY = exports.MS_GRPC_METHOD_KEY = exports.MS_PROVIDER_KEY = exports.MS_PRODUCER_KEY = exports.MS_CONSUMER_KEY = exports.RPC_DUBBO_KEY = exports.RPC_GRPC_KEY = exports.HSF_KEY = exports.WS_EVENT_KEY = exports.WS_CONTROLLER_KEY = exports.MODULE_TASK_QUEUE_OPTIONS = exports.MODULE_TASK_QUEUE_KEY = exports.MODULE_TASK_TASK_LOCAL_OPTIONS = exports.MODULE_TASK_TASK_LOCAL_KEY = exports.MODULE_TASK_METADATA = exports.MODULE_TASK_KEY = exports.WEB_RESPONSE_RENDER = exports.WEB_RESPONSE_CONTENT_TYPE = exports.WEB_RESPONSE_HEADER = exports.WEB_RESPONSE_REDIRECT = exports.WEB_RESPONSE_HTTP_CODE = exports.WEB_RESPONSE_KEY = exports.WEB_ROUTER_PARAM_KEY = exports.WEB_ROUTER_KEY = exports.CONTROLLER_KEY = exports.SERVERLESS_FUNC_KEY = exports.FUNC_KEY = exports.GUARD_KEY = exports.MATCH_KEY = exports.CATCH_KEY = exports.ASPECT_KEY = exports.FRAMEWORK_KEY = exports.CONFIGURATION_KEY = exports.SCHEDULE_KEY = exports.ALL = void 0;
4
- exports.PRIVATE_META_DATA_KEY = exports.MAIN_MODULE_KEY = exports.LIFECYCLE_IDENTIFIER_PREFIX = exports.PIPELINE_IDENTIFIER = void 0;
3
+ exports.TAGGED_FUN = exports.TAGGED_CLS = exports.INJECT_CUSTOM_PARAM = exports.INJECT_CUSTOM_METHOD = exports.INJECT_CUSTOM_PROPERTY = exports.INJECT_TAG = exports.NAMED_TAG = exports.CLASS_KEY_CONSTRUCTOR = exports.APPLICATION_CONTEXT_KEY = exports.APPLICATION_KEY = exports.LOGGER_KEY = exports.PLUGIN_KEY = exports.CONFIG_KEY = exports.MS_HSF_METHOD_KEY = exports.MS_DUBBO_METHOD_KEY = exports.MS_GRPC_METHOD_KEY = exports.MS_PROVIDER_KEY = exports.MS_PRODUCER_KEY = exports.MS_CONSUMER_KEY = exports.RPC_DUBBO_KEY = exports.RPC_GRPC_KEY = exports.HSF_KEY = exports.WS_EVENT_KEY = exports.WS_CONTROLLER_KEY = exports.MODULE_TASK_QUEUE_OPTIONS = exports.MODULE_TASK_QUEUE_KEY = exports.MODULE_TASK_TASK_LOCAL_OPTIONS = exports.MODULE_TASK_TASK_LOCAL_KEY = exports.MODULE_TASK_METADATA = exports.MODULE_TASK_KEY = exports.WEB_RESPONSE_RENDER = exports.WEB_RESPONSE_CONTENT_TYPE = exports.WEB_RESPONSE_HEADER = exports.WEB_RESPONSE_REDIRECT = exports.WEB_RESPONSE_HTTP_CODE = exports.WEB_RESPONSE_KEY = exports.WEB_ROUTER_PARAM_KEY = exports.WEB_ROUTER_KEY = exports.CONTROLLER_KEY = exports.SERVERLESS_FUNC_KEY = exports.FUNC_KEY = exports.FACTORY_SERVICE_CLIENT_KEY = exports.GUARD_KEY = exports.MATCH_KEY = exports.CATCH_KEY = exports.ASPECT_KEY = exports.FRAMEWORK_KEY = exports.CONFIGURATION_KEY = exports.SCHEDULE_KEY = exports.ALL = void 0;
4
+ exports.PRIVATE_META_DATA_KEY = exports.MAIN_MODULE_KEY = exports.LIFECYCLE_IDENTIFIER_PREFIX = exports.PIPELINE_IDENTIFIER = exports.OBJ_DEF_CLS = void 0;
5
5
  // got all value with no property name
6
6
  exports.ALL = 'common:all_value_key';
7
7
  // common
@@ -12,6 +12,7 @@ exports.ASPECT_KEY = 'common:aspect';
12
12
  exports.CATCH_KEY = 'common:catch';
13
13
  exports.MATCH_KEY = 'common:match';
14
14
  exports.GUARD_KEY = 'common:guard';
15
+ exports.FACTORY_SERVICE_CLIENT_KEY = 'common:service_factory:client';
15
16
  // faas
16
17
  exports.FUNC_KEY = 'faas:func';
17
18
  exports.SERVERLESS_FUNC_KEY = 'faas:serverless:function';
package/dist/index.d.ts CHANGED
@@ -19,6 +19,7 @@ export { RouterInfo, DynamicRouterInfo, RouterPriority, RouterCollectorOptions,
19
19
  export { MidwayServerlessFunctionService, WebRouterCollector, } from './service/slsFunctionService';
20
20
  export { CreateDataSourceInstanceOptions, DataSourceManager, } from './common/dataSourceManager';
21
21
  export * from './service/pipelineService';
22
+ export * from './common/loggerFactory';
22
23
  export * from './common/serviceFactory';
23
24
  export * from './common/dataListener';
24
25
  export * from './common/fileDetector';
package/dist/index.js CHANGED
@@ -54,6 +54,7 @@ Object.defineProperty(exports, "WebRouterCollector", { enumerable: true, get: fu
54
54
  var dataSourceManager_1 = require("./common/dataSourceManager");
55
55
  Object.defineProperty(exports, "DataSourceManager", { enumerable: true, get: function () { return dataSourceManager_1.DataSourceManager; } });
56
56
  __exportStar(require("./service/pipelineService"), exports);
57
+ __exportStar(require("./common/loggerFactory"), exports);
57
58
  __exportStar(require("./common/serviceFactory"), exports);
58
59
  __exportStar(require("./common/dataListener"), exports);
59
60
  __exportStar(require("./common/fileDetector"), exports);
@@ -1,9 +1,16 @@
1
1
  /// <reference types="node" />
2
- import type { ILogger, LoggerOptions, LoggerContextFormat } from '@midwayjs/logger';
2
+ import type { LoggerOptions, LoggerContextFormat } from '@midwayjs/logger';
3
3
  import * as EventEmitter from 'events';
4
4
  import type { AsyncContextManager } from './common/asyncContextManager';
5
+ import type { LoggerFactory } from './common/loggerFactory';
5
6
  import type { IManagedInstance, IMethodAspect, ObjectIdentifier } from './decorator';
6
7
  import { FrameworkType, ScopeEnum } from './decorator';
8
+ export interface ILogger {
9
+ info(msg: any, ...args: any[]): void;
10
+ debug(msg: any, ...args: any[]): void;
11
+ error(msg: any, ...args: any[]): void;
12
+ warn(msg: any, ...args: any[]): void;
13
+ }
7
14
  export interface MidwayCoreDefaultConfig {
8
15
  midwayLogger?: ServiceFactoryConfigOption<LoggerOptions>;
9
16
  debug?: {
@@ -22,6 +29,7 @@ export declare type ServiceFactoryConfigOption<OPTIONS> = {
22
29
  clients?: {
23
30
  [key: string]: PowerPartial<OPTIONS>;
24
31
  };
32
+ defaultClientName?: string;
25
33
  };
26
34
  export declare type DataSourceManagerConfigOption<OPTIONS> = {
27
35
  default?: PowerPartial<OPTIONS>;
@@ -473,6 +481,7 @@ export interface IMidwayBootstrapOptions {
473
481
  [environmentName: string]: Record<string, any>;
474
482
  }> | Record<string, any>;
475
483
  asyncContextManager?: AsyncContextManager;
484
+ loggerFactory?: LoggerFactory<any, any>;
476
485
  }
477
486
  export interface IConfigurationOptions {
478
487
  logger?: ILogger;
@@ -521,5 +530,13 @@ export interface MidwayAppInfo {
521
530
  export interface MidwayConfig extends FileConfigOption<MidwayCoreDefaultConfig> {
522
531
  [customConfigKey: string]: unknown;
523
532
  }
533
+ export interface IServiceFactory<Client> {
534
+ get(clientId: string): Client;
535
+ has(clientId: string): boolean;
536
+ createInstance(config: any, clientId?: string): Promise<Client | undefined>;
537
+ getName(): string;
538
+ stop(): Promise<void>;
539
+ getDefaultClientName(): string;
540
+ }
524
541
  export {};
525
542
  //# sourceMappingURL=interface.d.ts.map
@@ -40,7 +40,7 @@ let MidwayDecoratorService = class MidwayDecoratorService {
40
40
  if (!methodDecoratorHandler) {
41
41
  throw new error_1.MidwayCommonError(`Method Decorator "${key}" handler not found, please register first.`);
42
42
  }
43
- return this.methodDecoratorMap.get(key)({
43
+ return methodDecoratorHandler({
44
44
  target: Clzz,
45
45
  propertyName,
46
46
  metadata,
@@ -66,6 +66,21 @@ let MidwayFrameworkService = class MidwayFrameworkService {
66
66
  var _a;
67
67
  return this.getMainApp()[(_a = meta.identifier) !== null && _a !== void 0 ? _a : propertyName];
68
68
  });
69
+ this.decoratorService.registerPropertyHandler(decorator_1.FACTORY_SERVICE_CLIENT_KEY, (propertyName, meta) => {
70
+ const factory = this.applicationContext.get(meta.serviceFactoryClz);
71
+ const clientName = meta.clientName || factory.getDefaultClientName();
72
+ if (clientName && factory.has(clientName)) {
73
+ return factory.get(clientName);
74
+ }
75
+ else {
76
+ if (!clientName) {
77
+ throw new error_1.MidwayParameterError(`Please set clientName or options.defaultClientName for ${meta.serviceFactoryClz.name}).`);
78
+ }
79
+ else {
80
+ throw new error_1.MidwayParameterError(`ClientName(${clientName} not found in ${meta.serviceFactoryClz.name}).`);
81
+ }
82
+ }
83
+ });
69
84
  let frameworks = (0, decorator_1.listModule)(decorator_1.FRAMEWORK_KEY);
70
85
  // filter proto
71
86
  frameworks = filterProtoFramework(frameworks);
@@ -1,15 +1,18 @@
1
1
  import { MidwayConfigService } from './configService';
2
2
  import { ServiceFactory } from '../common/serviceFactory';
3
- import { ILogger, LoggerOptions } from '@midwayjs/logger';
4
- import { IMidwayContainer } from '../interface';
3
+ import { ILogger, IMidwayContainer } from '../interface';
4
+ import { LoggerFactory } from '../common/loggerFactory';
5
5
  export declare class MidwayLoggerService extends ServiceFactory<ILogger> {
6
6
  readonly applicationContext: IMidwayContainer;
7
+ readonly globalOptions: {};
7
8
  configService: MidwayConfigService;
8
- constructor(applicationContext: IMidwayContainer);
9
+ private loggerFactory;
10
+ constructor(applicationContext: IMidwayContainer, globalOptions?: {});
9
11
  protected init(): void;
10
- protected createClient(config: LoggerOptions, name?: string): void;
12
+ protected createClient(config: any, name?: string): void;
11
13
  getName(): string;
12
- createLogger(name: any, config: any): ILogger;
13
- getLogger(name: string): ILogger;
14
+ createLogger(name: any, config: any): any;
15
+ getLogger(name: string): any;
16
+ getCurrentLoggerFactory(): LoggerFactory<any, any>;
14
17
  }
15
18
  //# sourceMappingURL=loggerService.d.ts.map
@@ -15,27 +15,32 @@ const configService_1 = require("./configService");
15
15
  const serviceFactory_1 = require("../common/serviceFactory");
16
16
  const logger_1 = require("@midwayjs/logger");
17
17
  let MidwayLoggerService = class MidwayLoggerService extends serviceFactory_1.ServiceFactory {
18
- constructor(applicationContext) {
18
+ constructor(applicationContext, globalOptions = {}) {
19
19
  super();
20
20
  this.applicationContext = applicationContext;
21
+ this.globalOptions = globalOptions;
21
22
  }
22
23
  init() {
23
24
  var _a;
25
+ this.loggerFactory = this.globalOptions['loggerFactory'] || logger_1.loggers;
24
26
  this.initClients(this.configService.getConfiguration('midwayLogger'));
25
27
  // alias inject logger
26
28
  (_a = this.applicationContext) === null || _a === void 0 ? void 0 : _a.registerObject('logger', this.getLogger('appLogger'));
27
29
  }
28
30
  createClient(config, name) {
29
- logger_1.loggers.createLogger(name, config);
31
+ this.loggerFactory.createLogger(name, config);
30
32
  }
31
33
  getName() {
32
34
  return 'logger';
33
35
  }
34
36
  createLogger(name, config) {
35
- return logger_1.loggers.createLogger(name, config);
37
+ return this.loggerFactory.createLogger(name, config);
36
38
  }
37
39
  getLogger(name) {
38
- return logger_1.loggers.getLogger(name);
40
+ return this.loggerFactory.getLogger(name);
41
+ }
42
+ getCurrentLoggerFactory() {
43
+ return this.loggerFactory;
39
44
  }
40
45
  };
41
46
  __decorate([
@@ -51,7 +56,7 @@ __decorate([
51
56
  MidwayLoggerService = __decorate([
52
57
  (0, decorator_1.Provide)(),
53
58
  (0, decorator_1.Scope)(decorator_1.ScopeEnum.Singleton),
54
- __metadata("design:paramtypes", [Object])
59
+ __metadata("design:paramtypes", [Object, Object])
55
60
  ], MidwayLoggerService);
56
61
  exports.MidwayLoggerService = MidwayLoggerService;
57
62
  //# sourceMappingURL=loggerService.js.map
@@ -114,8 +114,6 @@ export declare class MidwayWebRouterService {
114
114
  private isReady;
115
115
  protected routes: Map<string, RouterInfo[]>;
116
116
  protected routesPriority: RouterPriority[];
117
- private cachedFlattenRouteList;
118
- private includeCompileUrlPattern;
119
117
  constructor(options?: RouterCollectorOptions);
120
118
  protected analyze(): Promise<void>;
121
119
  protected analyzeController(): void;
@@ -239,7 +237,6 @@ export declare class MidwayWebRouterService {
239
237
  getRouterTable(): Promise<Map<string, RouterInfo[]>>;
240
238
  getFlattenRouterTable(options?: {
241
239
  compileUrlPattern?: boolean;
242
- noCache?: boolean;
243
240
  }): Promise<RouterInfo[]>;
244
241
  getMatchedRouterInfo(routerUrl: string, method: string): Promise<RouterInfo | undefined>;
245
242
  protected checkDuplicateAndPush(prefix: any, routerInfo: RouterInfo): void;
@@ -23,7 +23,6 @@ let MidwayWebRouterService = class MidwayWebRouterService {
23
23
  this.isReady = false;
24
24
  this.routes = new Map();
25
25
  this.routesPriority = [];
26
- this.includeCompileUrlPattern = false;
27
26
  }
28
27
  async analyze() {
29
28
  this.analyzeController();
@@ -182,6 +181,8 @@ let MidwayWebRouterService = class MidwayWebRouterService {
182
181
  this.checkDuplicateAndPush(prefix, Object.assign(routerInfoOption, {
183
182
  method: routerFunction,
184
183
  }));
184
+ // sort again
185
+ this.sortPrefixAndRouter();
185
186
  }
186
187
  sortRouter(urlMatchList) {
187
188
  // 1. 绝对路径规则优先级最高如 /ab/cb/e
@@ -260,18 +261,6 @@ let MidwayWebRouterService = class MidwayWebRouterService {
260
261
  return this.routes;
261
262
  }
262
263
  async getFlattenRouterTable(options = {}) {
263
- if (this.cachedFlattenRouteList && !options.noCache) {
264
- if (options.compileUrlPattern && !this.includeCompileUrlPattern) {
265
- this.includeCompileUrlPattern = true;
266
- // attach match pattern function
267
- for (const item of this.cachedFlattenRouteList) {
268
- if (item.fullUrlFlattenString) {
269
- item.fullUrlCompiledRegexp = pathToRegexp_1.PathToRegexpUtil.toRegexp(item.fullUrlFlattenString);
270
- }
271
- }
272
- }
273
- return this.cachedFlattenRouteList;
274
- }
275
264
  if (!this.isReady) {
276
265
  await this.analyze();
277
266
  this.isReady = true;
@@ -281,7 +270,6 @@ let MidwayWebRouterService = class MidwayWebRouterService {
281
270
  routeArr = routeArr.concat(this.routes.get(routerPriority.prefix));
282
271
  }
283
272
  if (options.compileUrlPattern) {
284
- this.includeCompileUrlPattern = true;
285
273
  // attach match pattern function
286
274
  for (const item of routeArr) {
287
275
  if (item.fullUrlFlattenString) {
@@ -289,7 +277,6 @@ let MidwayWebRouterService = class MidwayWebRouterService {
289
277
  }
290
278
  }
291
279
  }
292
- this.cachedFlattenRouteList = routeArr;
293
280
  return routeArr;
294
281
  }
295
282
  async getMatchedRouterInfo(routerUrl, method) {
package/dist/setup.js CHANGED
@@ -6,7 +6,6 @@ const config_default_1 = require("./config/config.default");
6
6
  const decorator_1 = require("./decorator");
7
7
  const util = require("util");
8
8
  const path_1 = require("path");
9
- const logger_1 = require("@midwayjs/logger");
10
9
  const slsFunctionService_1 = require("./service/slsFunctionService");
11
10
  const debug = util.debuglog('midway:debug');
12
11
  /**
@@ -18,6 +17,7 @@ async function initializeGlobalApplicationContext(globalOptions) {
18
17
  // init logger
19
18
  const loggerService = await applicationContext.getAsync(_1.MidwayLoggerService, [
20
19
  applicationContext,
20
+ globalOptions,
21
21
  ]);
22
22
  if (loggerService.getLogger('appLogger')) {
23
23
  // register global logger
@@ -42,13 +42,15 @@ async function initializeGlobalApplicationContext(globalOptions) {
42
42
  }
43
43
  exports.initializeGlobalApplicationContext = initializeGlobalApplicationContext;
44
44
  async function destroyGlobalApplicationContext(applicationContext) {
45
+ const loggerService = await applicationContext.getAsync(_1.MidwayLoggerService);
46
+ const loggerFactory = loggerService.getCurrentLoggerFactory();
45
47
  // stop lifecycle
46
48
  const lifecycleService = await applicationContext.getAsync(_1.MidwayLifeCycleService);
47
49
  await lifecycleService.stop();
48
50
  // stop container
49
51
  await applicationContext.stop();
50
52
  (0, decorator_1.clearBindContainer)();
51
- logger_1.loggers.close();
53
+ loggerFactory.close();
52
54
  global['MIDWAY_APPLICATION_CONTEXT'] = undefined;
53
55
  global['MIDWAY_MAIN_FRAMEWORK'] = undefined;
54
56
  }
@@ -12,19 +12,19 @@ const preserveCamelCase = (string, toLowerCase, toUpperCase) => {
12
12
  let isLastCharLower = false;
13
13
  let isLastCharUpper = false;
14
14
  let isLastLastCharUpper = false;
15
- for (let i = 0; i < string.length; i++) {
16
- const character = string[i];
15
+ for (let index = 0; index < string.length; index++) {
16
+ const character = string[index];
17
17
  if (isLastCharLower && UPPERCASE.test(character)) {
18
- string = string.slice(0, i) + '-' + string.slice(i);
18
+ string = string.slice(0, index) + '-' + string.slice(index);
19
19
  isLastCharLower = false;
20
20
  isLastLastCharUpper = isLastCharUpper;
21
21
  isLastCharUpper = true;
22
- i++;
22
+ index++;
23
23
  }
24
24
  else if (isLastCharUpper &&
25
25
  isLastLastCharUpper &&
26
26
  LOWERCASE.test(character)) {
27
- string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
27
+ string = string.slice(0, index - 1) + '-' + string.slice(index - 1);
28
28
  isLastLastCharUpper = isLastCharUpper;
29
29
  isLastCharUpper = false;
30
30
  isLastCharLower = true;
@@ -60,6 +60,9 @@ function camelCaseOrigin(input, options) {
60
60
  const toLowerCase = string => string.toLowerCase();
61
61
  const toUpperCase = string => string.toUpperCase();
62
62
  if (input.length === 1) {
63
+ if (SEPARATORS.test(input)) {
64
+ return '';
65
+ }
63
66
  return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
64
67
  }
65
68
  const hasUpperCase = input !== toLowerCase(input);
@@ -5,11 +5,6 @@ const util = require("util");
5
5
  const ToString = Function.prototype.toString;
6
6
  const hasOwn = Object.prototype.hasOwnProperty;
7
7
  const toStr = Object.prototype.toString;
8
- function fnBody(fn) {
9
- return ToString.call(fn)
10
- .replace(/^[^{]*{\s*/, '')
11
- .replace(/\s*}[^}]*$/, '');
12
- }
13
8
  function isString(value) {
14
9
  return typeof value === 'string';
15
10
  }
@@ -21,10 +16,6 @@ function isClass(fn) {
21
16
  if (/^class[\s{]/.test(ToString.call(fn))) {
22
17
  return true;
23
18
  }
24
- // babel.js classCallCheck() & inlined
25
- const body = fnBody(fn);
26
- return (/classCallCheck\(/.test(body) ||
27
- /TypeError\("Cannot call a class as a function"\)/.test(body));
28
19
  }
29
20
  exports.isClass = isClass;
30
21
  function isAsyncFunction(value) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/core",
3
- "version": "3.7.0",
3
+ "version": "3.9.0",
4
4
  "description": "midway core",
5
5
  "main": "dist/index",
6
6
  "typings": "dist/index.d.ts",
@@ -23,10 +23,10 @@
23
23
  "license": "MIT",
24
24
  "devDependencies": {
25
25
  "koa": "2.13.4",
26
- "mm": "3.2.0",
26
+ "mm": "3.2.1",
27
27
  "pg": "8.8.0",
28
28
  "raw-body": "2.5.1",
29
- "sinon": "14.0.1"
29
+ "sinon": "14.0.2"
30
30
  },
31
31
  "dependencies": {
32
32
  "@midwayjs/glob": "^1.0.2",
@@ -38,10 +38,10 @@
38
38
  "author": "Harry Chen <czy88840616@gmail.com>",
39
39
  "repository": {
40
40
  "type": "git",
41
- "url": "http://github.com/midwayjs/midway.git"
41
+ "url": "https://github.com/midwayjs/midway.git"
42
42
  },
43
43
  "engines": {
44
44
  "node": ">=12"
45
45
  },
46
- "gitHead": "99386083ee26b386fd508b9c892091c914e77535"
46
+ "gitHead": "5f6603d2c9606fc6fc7ece71f956e89e394efeee"
47
47
  }