@midwayjs/web 3.0.11 → 3.0.14-beta.2

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.
@@ -19,7 +19,7 @@ module.exports = {
19
19
  if (this[ctxLogger]) {
20
20
  return this[ctxLogger];
21
21
  }
22
- return this.getLogger('logger');
22
+ return this.app.createContextLogger(this, 'logger');
23
23
  },
24
24
 
25
25
  set logger(customLogger) {
package/dist/base.js CHANGED
@@ -8,6 +8,8 @@ const fs_1 = require("fs");
8
8
  const logger_1 = require("./logger");
9
9
  const router_1 = require("@eggjs/router");
10
10
  const util_1 = require("util");
11
+ const lifecycle_1 = require("./framework/lifecycle");
12
+ const web_1 = require("./framework/web");
11
13
  const ROUTER = Symbol('EggCore#router');
12
14
  const EGG_LOADER = Symbol.for('egg#loader');
13
15
  const EGG_PATH = Symbol.for('egg#eggPath');
@@ -38,9 +40,6 @@ const createAppWorkerLoader = () => {
38
40
  this.useEggSocketIO = false;
39
41
  }
40
42
  getEggPaths() {
41
- if ((0, core_1.getCurrentApplicationContext)()) {
42
- this.singleProcessMode = true;
43
- }
44
43
  if (!this.appDir) {
45
44
  // 这里的逻辑是为了兼容老 cluster 模式
46
45
  if (this.app.options.typescript || this.app.options.isTsMode) {
@@ -104,19 +103,38 @@ const createAppWorkerLoader = () => {
104
103
  return serverEnv;
105
104
  }
106
105
  load() {
107
- if (!this.singleProcessMode) {
108
- // 多进程模式,从 egg-scripts 启动的
109
- process.env['EGG_CLUSTER_MODE'] = 'true';
110
- debug('[egg]: run with egg-scripts in cluster mode');
111
- // 如果不走 bootstrap,就得在这里初始化 applicationContext
112
- (0, core_1.initializeGlobalApplicationContext)({
113
- ...this.globalOptions,
114
- appDir: this.appDir,
115
- baseDir: this.baseDir,
116
- ignore: ['**/app/extend/**'],
117
- application: this.app,
118
- }).then(_ => {
119
- debug('[egg]: global context: init complete');
106
+ /**
107
+ * 由于使用了新的 hook 方式,这个时候 midway 已经初始化了一部分
108
+ * 但是我们把初始化分为了两个部分,framework 相关的留到这里初始化
109
+ * 避免 app 不存在,也能尽可能和单进程模式执行一样的逻辑
110
+ */
111
+ // lazy initialize framework
112
+ if (process.env['EGG_CLUSTER_MODE'] === 'true') {
113
+ this.app.beforeStart(async () => {
114
+ debug('[egg]: start "initialize framework service with lazy in app.load"');
115
+ const applicationContext = (0, core_1.getCurrentApplicationContext)();
116
+ applicationContext.bind(lifecycle_1.MidwayWebLifeCycleService);
117
+ /**
118
+ * 这里 logger service 已经被 get loggers() 初始化过了,就不需要在这里初始化了
119
+ */
120
+ // framework/config/plugin/logger/app decorator support
121
+ await applicationContext.getAsync(core_1.MidwayFrameworkService, [
122
+ applicationContext,
123
+ {
124
+ application: this.app,
125
+ },
126
+ ]);
127
+ this.app.once('server', async (server) => {
128
+ this.framework.setServer(server);
129
+ // register httpServer to applicationContext
130
+ applicationContext.registerObject(core_1.HTTP_SERVER_KEY, server);
131
+ await this.lifecycleService.afterInit();
132
+ });
133
+ // 这里生命周期走到 onReady
134
+ this.lifecycleService = await applicationContext.getAsync(lifecycle_1.MidwayWebLifeCycleService, [applicationContext]);
135
+ // 执行加载路由
136
+ this.framework = await applicationContext.getAsync(web_1.MidwayWebFramework);
137
+ await this.framework.loadMidwayController();
120
138
  });
121
139
  }
122
140
  }
@@ -126,15 +144,13 @@ const createAppWorkerLoader = () => {
126
144
  }
127
145
  loadConfig() {
128
146
  super.loadConfig();
129
- if (this.singleProcessMode) {
130
- const configService = (0, core_1.getCurrentApplicationContext)().get(core_1.MidwayConfigService);
131
- configService.addObject(this.config);
132
- Object.defineProperty(this, 'config', {
133
- get() {
134
- return configService.getConfiguration();
135
- },
136
- });
137
- }
147
+ const configService = (0, core_1.getCurrentApplicationContext)().get(core_1.MidwayConfigService);
148
+ configService.addObject(this.config, true);
149
+ Object.defineProperty(this, 'config', {
150
+ get() {
151
+ return configService.getConfiguration();
152
+ },
153
+ });
138
154
  }
139
155
  loadMiddleware() {
140
156
  super.loadMiddleware();
@@ -155,9 +171,6 @@ const createAgentWorkerLoader = () => {
155
171
  require('egg').AgentWorkerLoader;
156
172
  class EggAgentWorkerLoader extends AppWorkerLoader {
157
173
  getEggPaths() {
158
- if ((0, core_1.getCurrentApplicationContext)()) {
159
- this.singleProcessMode = true;
160
- }
161
174
  if (!this.appDir) {
162
175
  if (this.app.options.typescript || this.app.options.isTsMode) {
163
176
  process.env.EGG_TYPESCRIPT = 'true';
@@ -222,21 +235,16 @@ const createAgentWorkerLoader = () => {
222
235
  load() {
223
236
  this.app.beforeStart(async () => {
224
237
  debug('[egg]: start "initializeAgentApplicationContext"');
225
- await (0, utils_1.initializeAgentApplicationContext)(this.app, {
226
- ...this.globalOptions,
227
- appDir: this.appDir,
228
- baseDir: this.baseDir,
229
- ignore: ['**/app/extend/**'],
230
- });
238
+ await (0, utils_1.initializeAgentApplicationContext)(this.app);
231
239
  super.load();
232
240
  debug('[egg]: agent load run complete');
233
241
  });
234
242
  }
235
243
  loadConfig() {
236
244
  super.loadConfig();
237
- if (this.singleProcessMode) {
245
+ if ((0, core_1.getCurrentApplicationContext)()) {
238
246
  const configService = (0, core_1.getCurrentApplicationContext)().get(core_1.MidwayConfigService);
239
- configService.addObject(this.config);
247
+ configService.addObject(this.config, true);
240
248
  Object.defineProperty(this, 'config', {
241
249
  get() {
242
250
  return configService.getConfiguration();
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=cluster.d.ts.map
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const core_1 = require("@midwayjs/core");
4
+ const path_1 = require("path");
5
+ const utils_1 = require("./utils");
6
+ const util_1 = require("util");
7
+ const debug = (0, util_1.debuglog)('midway:debug');
8
+ function runInAgent() {
9
+ return (process.title.indexOf('agent') !== -1 ||
10
+ (process.argv[1] && process.argv[1].indexOf('agent_worker') !== -1));
11
+ }
12
+ // 多进程模式,从 egg-scripts 启动的
13
+ process.env['EGG_CLUSTER_MODE'] = 'true';
14
+ const isAgent = runInAgent();
15
+ debug('[egg]: run with egg-scripts in worker and init midway container in cluster mode');
16
+ const appDir = process.cwd();
17
+ let baseDir;
18
+ if ((0, utils_1.isTypeScriptEnvironment)()) {
19
+ baseDir = (0, path_1.join)(appDir, 'src');
20
+ }
21
+ else {
22
+ baseDir = (0, path_1.join)(appDir, 'dist');
23
+ }
24
+ (0, core_1.initializeGlobalApplicationContext)({
25
+ appDir,
26
+ baseDir,
27
+ ignore: ['**/app/extend/**'],
28
+ lazyInitializeFramework: true,
29
+ });
30
+ if (!isAgent) {
31
+ debug('[egg]: run with egg-scripts in worker and init midway container complete');
32
+ }
33
+ else {
34
+ debug('[egg]: run with egg-scripts in agent and init midway container complete');
35
+ }
36
+ //# sourceMappingURL=cluster.js.map
@@ -0,0 +1,3 @@
1
+ declare const _default: (appInfo: any) => any;
2
+ export default _default;
3
+ //# sourceMappingURL=config.default.d.ts.map
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const path = require("path");
4
+ const mkdirp = require("mkdirp");
5
+ const os = require("os");
6
+ const fs = require("fs");
7
+ exports.default = appInfo => {
8
+ const exports = {};
9
+ exports.rundir = path.join(appInfo.appDir, 'run');
10
+ // 修改默认的日志名
11
+ exports.midwayLogger = {
12
+ clients: {
13
+ appLogger: {
14
+ fileLogName: 'midway-web.log',
15
+ aliasName: 'logger',
16
+ },
17
+ agentLogger: {
18
+ fileLogName: 'midway-agent.log',
19
+ },
20
+ },
21
+ };
22
+ exports.egg = {
23
+ dumpConfig: true,
24
+ contextLoggerFormat: info => {
25
+ const ctx = info.ctx;
26
+ // format: '[$userId/$ip/$traceId/$use_ms $method $url]'
27
+ const userId = ctx.userId || '-';
28
+ const traceId = (ctx.tracer && ctx.tracer.traceId) || '-';
29
+ const use = Date.now() - ctx.startTime;
30
+ const label = userId +
31
+ '/' +
32
+ ctx.ip +
33
+ '/' +
34
+ traceId +
35
+ '/' +
36
+ use +
37
+ 'ms ' +
38
+ ctx.method +
39
+ ' ' +
40
+ ctx.url;
41
+ return `${info.timestamp} ${info.LEVEL} ${info.pid} [${label}] ${info.message}`;
42
+ },
43
+ };
44
+ exports.pluginOverwrite = false;
45
+ exports.security = {
46
+ csrf: {
47
+ ignoreJSON: false,
48
+ },
49
+ };
50
+ // alinode runtime 写入的日志策略是: 如果 NODE_LOG_DIR 有设置,写入 NODE_LOG_DIR 设置的目录;否则为 /tmp
51
+ let alinodeLogdir = fs.existsSync('/tmp') ? '/tmp' : os.tmpdir();
52
+ // try to use NODE_LOG_DIR first
53
+ if (process.env.NODE_LOG_DIR) {
54
+ alinodeLogdir = process.env.NODE_LOG_DIR;
55
+ }
56
+ mkdirp.sync(alinodeLogdir);
57
+ exports.alinode = {
58
+ logdir: alinodeLogdir,
59
+ error_log: [
60
+ path.join(appInfo.root, `logs/${appInfo.pkg.name}/common-error.log`),
61
+ path.join(appInfo.root, 'logs/stderr.log'),
62
+ ],
63
+ packages: [path.join(appInfo.appDir, 'package.json')],
64
+ };
65
+ return exports;
66
+ };
67
+ //# sourceMappingURL=config.default.js.map
@@ -0,0 +1,9 @@
1
+ export declare const egg: {
2
+ plugins: {
3
+ 'egg-mock': {
4
+ enable: boolean;
5
+ package: string;
6
+ };
7
+ };
8
+ };
9
+ //# sourceMappingURL=config.local.d.ts.map
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.egg = void 0;
4
+ exports.egg = {
5
+ plugins: {
6
+ 'egg-mock': {
7
+ enable: true,
8
+ package: 'egg-mock',
9
+ },
10
+ },
11
+ };
12
+ //# sourceMappingURL=config.local.js.map
@@ -0,0 +1,9 @@
1
+ export declare const egg: {
2
+ plugins: {
3
+ 'egg-mock': {
4
+ enable: boolean;
5
+ package: string;
6
+ };
7
+ };
8
+ };
9
+ //# sourceMappingURL=config.unittest.d.ts.map
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.egg = void 0;
4
+ exports.egg = {
5
+ plugins: {
6
+ 'egg-mock': {
7
+ enable: true,
8
+ package: 'egg-mock',
9
+ },
10
+ },
11
+ };
12
+ //# sourceMappingURL=config.unittest.js.map
@@ -12,6 +12,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.EggConfiguration = void 0;
13
13
  const decorator_1 = require("@midwayjs/decorator");
14
14
  const core_1 = require("@midwayjs/core");
15
+ const path_1 = require("path");
15
16
  let EggConfiguration = class EggConfiguration {
16
17
  init() {
17
18
  this.decoratorService.registerParameterHandler(decorator_1.WEB_ROUTER_PARAM_KEY, options => {
@@ -59,65 +60,7 @@ __decorate([
59
60
  EggConfiguration = __decorate([
60
61
  (0, decorator_1.Configuration)({
61
62
  namespace: 'egg',
62
- importConfigs: [
63
- {
64
- default: {
65
- midwayLogger: {
66
- clients: {
67
- appLogger: {
68
- fileLogName: 'midway-web.log',
69
- aliasName: 'logger',
70
- },
71
- agentLogger: {
72
- fileLogName: 'midway-agent.log',
73
- },
74
- },
75
- },
76
- egg: {
77
- dumpConfig: true,
78
- contextLoggerFormat: info => {
79
- const ctx = info.ctx;
80
- // format: '[$userId/$ip/$traceId/$use_ms $method $url]'
81
- const userId = ctx.userId || '-';
82
- const traceId = (ctx.tracer && ctx.tracer.traceId) || '-';
83
- const use = Date.now() - ctx.startTime;
84
- const label = userId +
85
- '/' +
86
- ctx.ip +
87
- '/' +
88
- traceId +
89
- '/' +
90
- use +
91
- 'ms ' +
92
- ctx.method +
93
- ' ' +
94
- ctx.url;
95
- return `${info.timestamp} ${info.LEVEL} ${info.pid} [${label}] ${info.message}`;
96
- },
97
- },
98
- },
99
- test: {
100
- egg: {
101
- plugins: {
102
- 'egg-mock': {
103
- enable: true,
104
- package: 'egg-mock',
105
- },
106
- },
107
- },
108
- },
109
- unittest: {
110
- egg: {
111
- plugins: {
112
- 'egg-mock': {
113
- enable: true,
114
- package: 'egg-mock',
115
- },
116
- },
117
- },
118
- },
119
- },
120
- ],
63
+ importConfigs: [(0, path_1.join)(__dirname, 'config')],
121
64
  })
122
65
  ], EggConfiguration);
123
66
  exports.EggConfiguration = EggConfiguration;
@@ -0,0 +1,14 @@
1
+ import { IMidwayContainer, MidwayConfigService, MidwayFrameworkService } from '@midwayjs/core';
2
+ export declare class MidwayWebLifeCycleService {
3
+ readonly applicationContext: IMidwayContainer;
4
+ protected frameworkService: MidwayFrameworkService;
5
+ protected configService: MidwayConfigService;
6
+ private lifecycleInstanceList;
7
+ constructor(applicationContext: IMidwayContainer);
8
+ protected init(): Promise<void>;
9
+ afterInit(): Promise<void>;
10
+ stop(): Promise<void>;
11
+ private runContainerLifeCycle;
12
+ private runObjectLifeCycle;
13
+ }
14
+ //# sourceMappingURL=lifecycle.d.ts.map
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.MidwayWebLifeCycleService = void 0;
13
+ const core_1 = require("@midwayjs/core");
14
+ const decorator_1 = require("@midwayjs/decorator");
15
+ const configuration_1 = require("@midwayjs/core/dist/functional/configuration");
16
+ const util_1 = require("util");
17
+ const debug = (0, util_1.debuglog)('midway:debug');
18
+ let MidwayWebLifeCycleService = class MidwayWebLifeCycleService {
19
+ constructor(applicationContext) {
20
+ this.applicationContext = applicationContext;
21
+ this.lifecycleInstanceList = [];
22
+ }
23
+ async init() {
24
+ // run lifecycle
25
+ const cycles = (0, decorator_1.listModule)(decorator_1.CONFIGURATION_KEY);
26
+ debug(`[core]: Found Configuration length = ${cycles.length}`);
27
+ for (const cycle of cycles) {
28
+ if (cycle.target instanceof configuration_1.FunctionalConfiguration) {
29
+ // 函数式写法
30
+ cycle.instance = cycle.target;
31
+ }
32
+ else {
33
+ // 普通类写法
34
+ debug(`[core]: Lifecycle run ${cycle.target.name} init`);
35
+ cycle.instance = await this.applicationContext.getAsync(cycle.target);
36
+ }
37
+ if (cycle.instance) {
38
+ this.lifecycleInstanceList.push(cycle);
39
+ }
40
+ }
41
+ // bind object lifecycle
42
+ await Promise.all([
43
+ this.runObjectLifeCycle(this.lifecycleInstanceList, 'onBeforeObjectCreated'),
44
+ this.runObjectLifeCycle(this.lifecycleInstanceList, 'onObjectCreated'),
45
+ this.runObjectLifeCycle(this.lifecycleInstanceList, 'onObjectInit'),
46
+ this.runObjectLifeCycle(this.lifecycleInstanceList, 'onBeforeObjectDestroy'),
47
+ ]);
48
+ // bind framework lifecycle
49
+ // onAppError
50
+ // exec onConfigLoad()
51
+ await this.runContainerLifeCycle(this.lifecycleInstanceList, 'onConfigLoad', configData => {
52
+ if (configData) {
53
+ this.configService.addObject(configData);
54
+ }
55
+ });
56
+ // exec onReady()
57
+ await this.runContainerLifeCycle(this.lifecycleInstanceList, 'onReady');
58
+ }
59
+ async afterInit() {
60
+ // exec framework.run()
61
+ await this.frameworkService.runFramework();
62
+ // exec onServerReady()
63
+ await this.runContainerLifeCycle(this.lifecycleInstanceList, 'onServerReady');
64
+ // clear config merge cache
65
+ if (!this.configService.getConfiguration('debug.recordConfigMergeOrder')) {
66
+ this.configService.clearConfigMergeOrder();
67
+ }
68
+ }
69
+ async stop() {
70
+ // stop lifecycle
71
+ const cycles = (0, decorator_1.listModule)(decorator_1.CONFIGURATION_KEY);
72
+ for (const cycle of cycles) {
73
+ let inst;
74
+ if (cycle.target instanceof configuration_1.FunctionalConfiguration) {
75
+ // 函数式写法
76
+ inst = cycle.target;
77
+ }
78
+ else {
79
+ inst = await this.applicationContext.getAsync(cycle.target);
80
+ }
81
+ await this.runContainerLifeCycle(inst, 'onStop');
82
+ }
83
+ // stop framework
84
+ await this.frameworkService.stopFramework();
85
+ }
86
+ async runContainerLifeCycle(lifecycleInstanceOrList, lifecycle, resultHandler) {
87
+ if (Array.isArray(lifecycleInstanceOrList)) {
88
+ for (const cycle of lifecycleInstanceOrList) {
89
+ if (typeof cycle.instance[lifecycle] === 'function') {
90
+ debug(`[core]: Lifecycle run ${cycle.instance.constructor.name} ${lifecycle}`);
91
+ const result = await cycle.instance[lifecycle](this.applicationContext, this.frameworkService.getMainApp());
92
+ if (resultHandler) {
93
+ resultHandler(result);
94
+ }
95
+ }
96
+ }
97
+ }
98
+ else {
99
+ if (typeof lifecycleInstanceOrList[lifecycle] === 'function') {
100
+ debug(`[core]: Lifecycle run ${lifecycleInstanceOrList.constructor.name} ${lifecycle}`);
101
+ const result = await lifecycleInstanceOrList[lifecycle](this.applicationContext, this.frameworkService.getMainApp());
102
+ if (resultHandler) {
103
+ resultHandler(result);
104
+ }
105
+ }
106
+ }
107
+ }
108
+ async runObjectLifeCycle(lifecycleInstanceList, lifecycle) {
109
+ for (const cycle of lifecycleInstanceList) {
110
+ if (typeof cycle.instance[lifecycle] === 'function') {
111
+ debug(`[core]: Lifecycle run ${cycle.instance.constructor.name} ${lifecycle}`);
112
+ return this.applicationContext[lifecycle](cycle.instance[lifecycle].bind(cycle.instance));
113
+ }
114
+ }
115
+ }
116
+ };
117
+ __decorate([
118
+ (0, decorator_1.Inject)(),
119
+ __metadata("design:type", core_1.MidwayFrameworkService)
120
+ ], MidwayWebLifeCycleService.prototype, "frameworkService", void 0);
121
+ __decorate([
122
+ (0, decorator_1.Inject)(),
123
+ __metadata("design:type", core_1.MidwayConfigService)
124
+ ], MidwayWebLifeCycleService.prototype, "configService", void 0);
125
+ __decorate([
126
+ (0, decorator_1.Init)(),
127
+ __metadata("design:type", Function),
128
+ __metadata("design:paramtypes", []),
129
+ __metadata("design:returntype", Promise)
130
+ ], MidwayWebLifeCycleService.prototype, "init", null);
131
+ MidwayWebLifeCycleService = __decorate([
132
+ (0, decorator_1.Provide)(),
133
+ (0, decorator_1.Scope)(decorator_1.ScopeEnum.Singleton),
134
+ __metadata("design:paramtypes", [Object])
135
+ ], MidwayWebLifeCycleService);
136
+ exports.MidwayWebLifeCycleService = MidwayWebLifeCycleService;
137
+ //# sourceMappingURL=lifecycle.js.map
@@ -29,6 +29,7 @@ export declare class MidwayWebFramework extends BaseFramework<Application, Conte
29
29
  setContextLoggerClass(): void;
30
30
  generateMiddleware(middlewareId: any): Promise<any>;
31
31
  beforeStop(): Promise<void>;
32
+ setServer(server: any): void;
32
33
  }
33
34
  export {};
34
35
  //# sourceMappingURL=web.d.ts.map
@@ -87,17 +87,19 @@ let MidwayWebFramework = class MidwayWebFramework extends core_1.BaseFramework {
87
87
  this.app.use(midwayRootMiddleware);
88
88
  this.generator = new EggControllerGenerator(this.app);
89
89
  this.overwriteApplication('app');
90
- await new Promise(resolve => {
91
- this.app.once('application-ready', () => {
92
- debug('[egg]: web framework: init egg end');
93
- resolve();
90
+ this.app.loader.loadOrigin();
91
+ // 这里拦截 app.use 方法,让他可以加到 midway 的 middlewareManager 中
92
+ this.app.originUse = this.app.use;
93
+ this.app.use = this.app.useMiddleware;
94
+ if (!this.isClusterMode) {
95
+ await new Promise(resolve => {
96
+ this.app.once('application-ready', () => {
97
+ debug('[egg]: web framework: init egg end');
98
+ resolve();
99
+ });
100
+ this.app.ready();
94
101
  });
95
- this.app.loader.loadOrigin();
96
- // 这里拦截 app.use 方法,让他可以加到 midway 的 middlewareManager 中
97
- this.app.originUse = this.app.use;
98
- this.app.use = this.app.useMiddleware;
99
- this.app.ready();
100
- });
102
+ }
101
103
  }
102
104
  overwriteApplication(processType) {
103
105
  // eslint-disable-next-line @typescript-eslint/no-this-alias
@@ -136,32 +138,36 @@ let MidwayWebFramework = class MidwayWebFramework extends core_1.BaseFramework {
136
138
  return core_1.MidwayProcessTypeEnum.AGENT;
137
139
  }
138
140
  },
141
+ createContextLogger: (ctx, name) => {
142
+ return this.createContextLogger(ctx, name);
143
+ },
139
144
  }, ['createAnonymousContext']);
140
145
  // if use midway logger will be use midway custom context logger
141
146
  debug(`[egg]: overwrite BaseContextLoggerClass to "${processType}"`);
142
147
  this.setContextLoggerClass();
143
148
  }
144
149
  async loadMidwayController() {
150
+ // move egg router to last
151
+ this.app.getMiddleware().findAndInsertLast('eggRouterMiddleware');
145
152
  await this.generator.loadMidwayController(this.configurationOptions.globalPrefix, newRouter => {
146
153
  var _a;
147
154
  const dispatchFn = newRouter.middleware();
148
155
  dispatchFn._name = `midwayController(${((_a = newRouter === null || newRouter === void 0 ? void 0 : newRouter.opts) === null || _a === void 0 ? void 0 : _a.prefix) || '/'})`;
149
156
  this.app.useMiddleware(dispatchFn);
150
157
  });
158
+ // restore use method
159
+ this.app.use = this.app.originUse;
160
+ debug(`[egg]: current middleware = ${this.middlewareManager.getNames()}`);
151
161
  }
152
162
  getFrameworkType() {
153
163
  return decorator_1.MidwayFrameworkType.WEB;
154
164
  }
155
165
  async run() {
156
166
  var _a;
157
- // move egg router to last
158
- this.app.getMiddleware().findAndInsertLast('eggRouterMiddleware');
159
- // load controller
160
- await this.loadMidwayController();
161
- // restore use method
162
- this.app.use = this.app.originUse;
163
- debug(`[egg]: current middleware = ${this.middlewareManager.getNames()}`);
167
+ // cluster 模式加载路由需在 run 之前,因为 run 需要在拿到 server 之后执行
164
168
  if (!this.isClusterMode) {
169
+ // load controller
170
+ await this.loadMidwayController();
165
171
  // https config
166
172
  if (this.configurationOptions.key && this.configurationOptions.cert) {
167
173
  this.configurationOptions.key = core_1.PathFileUtil.getFileContentSync(this.configurationOptions.key);
@@ -238,6 +244,9 @@ let MidwayWebFramework = class MidwayWebFramework extends core_1.BaseFramework {
238
244
  await this.agent.close();
239
245
  }
240
246
  }
247
+ setServer(server) {
248
+ this.server = server;
249
+ }
241
250
  };
242
251
  __decorate([
243
252
  (0, decorator_1.Inject)(),
package/dist/index.d.ts CHANGED
@@ -2,6 +2,6 @@ export * from './interface';
2
2
  export { MidwayWebFramework as Framework } from './framework/web';
3
3
  export { createEggApplication, createEggAgent, createAppWorkerLoader, createAgentWorkerLoader, } from './base';
4
4
  export { Application, Agent } from './application';
5
- export { startCluster } from 'egg';
6
5
  export { EggConfiguration as Configuration } from './configuration';
6
+ export declare function startCluster(serverConfig: any, callback?: any): any;
7
7
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -10,7 +10,9 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
10
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.Configuration = exports.startCluster = exports.Agent = exports.Application = exports.createAgentWorkerLoader = exports.createAppWorkerLoader = exports.createEggAgent = exports.createEggApplication = exports.Framework = void 0;
13
+ exports.startCluster = exports.Configuration = exports.Agent = exports.Application = exports.createAgentWorkerLoader = exports.createAppWorkerLoader = exports.createEggAgent = exports.createEggApplication = exports.Framework = void 0;
14
+ const egg_cluster_1 = require("egg-cluster");
15
+ const path_1 = require("path");
14
16
  __exportStar(require("./interface"), exports);
15
17
  var web_1 = require("./framework/web");
16
18
  Object.defineProperty(exports, "Framework", { enumerable: true, get: function () { return web_1.MidwayWebFramework; } });
@@ -22,8 +24,17 @@ Object.defineProperty(exports, "createAgentWorkerLoader", { enumerable: true, ge
22
24
  var application_1 = require("./application");
23
25
  Object.defineProperty(exports, "Application", { enumerable: true, get: function () { return application_1.Application; } });
24
26
  Object.defineProperty(exports, "Agent", { enumerable: true, get: function () { return application_1.Agent; } });
25
- var egg_1 = require("egg");
26
- Object.defineProperty(exports, "startCluster", { enumerable: true, get: function () { return egg_1.startCluster; } });
27
27
  var configuration_1 = require("./configuration");
28
28
  Object.defineProperty(exports, "Configuration", { enumerable: true, get: function () { return configuration_1.EggConfiguration; } });
29
+ function startCluster(serverConfig, callback) {
30
+ if (!serverConfig['require']) {
31
+ serverConfig['require'] = [];
32
+ }
33
+ if (!Array.isArray(serverConfig['require'])) {
34
+ serverConfig['require'] = [serverConfig['require']];
35
+ }
36
+ serverConfig['require'].push((0, path_1.join)(__dirname, 'cluster'));
37
+ return (0, egg_cluster_1.startCluster)(serverConfig, callback);
38
+ }
39
+ exports.startCluster = startCluster;
29
40
  //# sourceMappingURL=index.js.map