ee-core 1.5.2-beta.1 → 2.0.0-beta.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 +21 -21
- package/README.md +2 -2
- package/addon/window/index.js +91 -91
- package/bin/tools.js +18 -18
- package/config/config.default.js +287 -280
- package/core/index.js +12 -12
- package/core/lib/ee.js +218 -218
- package/core/lib/loader/context_loader.js +106 -106
- package/core/lib/loader/ee_loader.js +461 -457
- package/core/lib/loader/file_loader.js +325 -325
- package/core/lib/loader/mixin/addon.js +32 -32
- package/core/lib/loader/mixin/config.js +135 -135
- package/core/lib/loader/mixin/controller.js +125 -124
- package/core/lib/loader/mixin/service.js +28 -28
- package/core/lib/utils/base_context_class.js +34 -34
- package/core/lib/utils/function.js +30 -0
- package/core/lib/utils/index.js +127 -127
- package/core/lib/utils/sequencify.js +59 -59
- package/core/lib/utils/timing.js +77 -77
- package/index.js +49 -49
- package/lib/appLoader.js +48 -53
- package/lib/application.js +85 -84
- package/lib/baseApp.js +114 -131
- package/lib/eeApp.js +325 -359
- package/{lib/constant.js → module/const/index.js} +12 -9
- package/{lib/httpclient.js → module/httpclient/index.js} +170 -136
- package/module/jobs/child/forkProcess.js +99 -0
- package/module/jobs/child/index.js +33 -0
- package/module/jobs/index.js +55 -0
- package/module/jobs/renderer/index.js +140 -0
- package/module/jobs/renderer/loadView.js +40 -0
- package/module/loader/index.js +78 -0
- package/module/log/index.js +53 -0
- package/module/log/logger.js +61 -0
- package/module/message/index.js +13 -0
- package/module/message/ipcMain.js +160 -0
- package/module/message/ipcRender.js +0 -0
- package/{lib → module}/socket/httpServer.js +142 -142
- package/{lib → module}/socket/io.js +23 -23
- package/{lib → module}/socket/ipcServer.js +106 -108
- package/{lib → module}/socket/socketClient.js +51 -50
- package/{lib → module}/socket/socketServer.js +77 -76
- package/module/socket/start.js +22 -0
- package/{lib → module}/storage/index.js +35 -34
- package/module/storage/jsondb/adapters/Base.js +14 -0
- package/module/storage/jsondb/adapters/FileSync.js +32 -0
- package/{lib/storage/lowdb → module/storage/jsondb}/main.js +42 -46
- package/{lib/storage/lowdbStorage.js → module/storage/jsondbStorage.js} +98 -99
- package/{lib → module}/storage/sqliteStorage.js +123 -127
- package/module/utils/copyto.js +161 -0
- package/module/utils/helper.js +117 -0
- package/module/utils/index.js +120 -0
- package/module/utils/json.js +72 -0
- package/module/utils/ps.js +175 -0
- package/{utils → module/utils}/wrap.js +35 -37
- package/package.json +44 -48
- package/tools/encrypt.js +274 -274
- package/tools/replaceDist.js +61 -61
- package/utils/index.js +128 -246
- package/lib/logger.js +0 -47
- package/lib/socket/start.js +0 -22
- package/lib/storage/lowdb/adapters/Base.js +0 -15
- package/lib/storage/lowdb/adapters/FileAsync.js +0 -41
- package/lib/storage/lowdb/adapters/FileSync.js +0 -39
- package/lib/storage/lowdb/adapters/LocalStorage.js +0 -20
- package/lib/storage/lowdb/adapters/Memory.js +0 -8
- package/lib/storage/lowdb/adapters/_stringify.js +0 -4
- package/lib/storage/lowdb/common.js +0 -33
- package/lib/storage/lowdb/fp.js +0 -23
- package/lib/storage/lowdb/is-promise.js +0 -6
- package/lib/storage/lowdb/nano.js +0 -5
- package/utils/common.js +0 -91
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
const Ps = require('../../utils/ps');
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* loadView 生成BrowserWindow的html content
|
|
5
|
+
*/
|
|
6
|
+
const loadView = function (opt = {}) {
|
|
7
|
+
const webSecurity = opt.webSecurity;
|
|
8
|
+
const src = opt.src;
|
|
9
|
+
const title = opt.title;
|
|
10
|
+
const script = opt.script;
|
|
11
|
+
|
|
12
|
+
//const scriptUrl = new URL('eefile://' + src);
|
|
13
|
+
const scriptUrl = 'eefile://' + src;
|
|
14
|
+
console.log('[ee-core:job] scriptUrl: ', scriptUrl);
|
|
15
|
+
|
|
16
|
+
// 脚本内容
|
|
17
|
+
//const scriptBytenode = Ps.isDev() ? '' : `<script> require('bytenode') </script>`;
|
|
18
|
+
const scriptContent = webSecurity ? `<script> ${ script } </script>` : `<script src='${scriptUrl}'></script>`;
|
|
19
|
+
|
|
20
|
+
// html内容
|
|
21
|
+
const htmlContent = (`
|
|
22
|
+
<!DOCTYPE html>
|
|
23
|
+
<html>
|
|
24
|
+
<head>
|
|
25
|
+
<title>${title}</title>
|
|
26
|
+
<meta charset="UTF-8">
|
|
27
|
+
</head>
|
|
28
|
+
<body>
|
|
29
|
+
${scriptContent}
|
|
30
|
+
</body>
|
|
31
|
+
</html>
|
|
32
|
+
`);
|
|
33
|
+
|
|
34
|
+
const DataURI = 'data:text/html;charset=UTF-8,';
|
|
35
|
+
const data = DataURI + encodeURIComponent(htmlContent);
|
|
36
|
+
|
|
37
|
+
return data;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
module.exports = loadView;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
const is = require('is-type-of');
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const UtilsCore = require('../../core/lib/utils');
|
|
5
|
+
const Ps = require('../utils/ps');
|
|
6
|
+
|
|
7
|
+
module.exports = {
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* 加载单个文件(如果是函数,将被执行)
|
|
11
|
+
*
|
|
12
|
+
* @param {String} filepath - fullpath
|
|
13
|
+
* @param {Array} inject - pass rest arguments into the function when invoke
|
|
14
|
+
* @return {Object} exports
|
|
15
|
+
* @since 1.0.0
|
|
16
|
+
*/
|
|
17
|
+
loadFile (filepath, ...inject) {
|
|
18
|
+
filepath = filepath && this.resolveModule(filepath);
|
|
19
|
+
if (!filepath) {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const ret = UtilsCore.loadFile(filepath);
|
|
24
|
+
if (is.function(ret) && !is.class(ret) && !UtilsCore.isBytecodeClass(ret)) {
|
|
25
|
+
ret = ret(...inject);
|
|
26
|
+
}
|
|
27
|
+
return ret;
|
|
28
|
+
},
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 模块的绝对路径
|
|
32
|
+
*/
|
|
33
|
+
resolveModule(filepath) {
|
|
34
|
+
const isAbsolute = path.isAbsolute(filepath);
|
|
35
|
+
if (!isAbsolute) {
|
|
36
|
+
filepath = path.join(Ps.getBaseDir(), 'jobs', filepath);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
let fullPath;
|
|
40
|
+
try {
|
|
41
|
+
fullPath = require.resolve(filepath);
|
|
42
|
+
} catch (e) {
|
|
43
|
+
let jscFile = filepath + '.jsc';
|
|
44
|
+
if (fs.existsSync(jscFile)) {
|
|
45
|
+
return jscFile;
|
|
46
|
+
}
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
return fullPath;
|
|
51
|
+
},
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 加载模块(子进程中使用)
|
|
55
|
+
*
|
|
56
|
+
* @param {String} filepath - fullpath
|
|
57
|
+
* @return {Object} exports
|
|
58
|
+
* @since 1.0.0
|
|
59
|
+
*/
|
|
60
|
+
requireModule (filepath) {
|
|
61
|
+
filepath = filepath && this.resolveModule(filepath);
|
|
62
|
+
if (!filepath) {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
const ret = UtilsCore.loadFile(filepath);
|
|
66
|
+
|
|
67
|
+
return ret;
|
|
68
|
+
},
|
|
69
|
+
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
const Logger = require('./logger');
|
|
2
|
+
const EELoggers = Symbol('EeApplication#EELoggers');
|
|
3
|
+
|
|
4
|
+
const Log = {
|
|
5
|
+
/**
|
|
6
|
+
* 创建日志实例
|
|
7
|
+
*/
|
|
8
|
+
create (config) {
|
|
9
|
+
const eeLog = Logger.create(config);
|
|
10
|
+
|
|
11
|
+
return eeLog;
|
|
12
|
+
},
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* logger
|
|
16
|
+
*/
|
|
17
|
+
get logger() {
|
|
18
|
+
if (!this[EELoggers]) {
|
|
19
|
+
this[EELoggers] = Logger.create();
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
return this[EELoggers]['logger'] || null;
|
|
23
|
+
},
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* coreLogger
|
|
27
|
+
*/
|
|
28
|
+
get coreLogger () {
|
|
29
|
+
if (!this[EELoggers]) {
|
|
30
|
+
this[EELoggers] = Logger.create();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
return this[EELoggers]['coreLogger'] || null;
|
|
34
|
+
},
|
|
35
|
+
|
|
36
|
+
get error() {
|
|
37
|
+
return this.logger.error.bind(this.logger);
|
|
38
|
+
},
|
|
39
|
+
|
|
40
|
+
get warn() {
|
|
41
|
+
return this.logger.warn.bind(this.logger);
|
|
42
|
+
},
|
|
43
|
+
|
|
44
|
+
get info() {
|
|
45
|
+
return this.logger.info.bind(this.logger);
|
|
46
|
+
},
|
|
47
|
+
|
|
48
|
+
get debug() {
|
|
49
|
+
return this.logger.debug.bind(this.logger);
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
module.exports = Log;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
const Loggers = require('egg-logger').EggLoggers;
|
|
2
|
+
const assert = require('assert');
|
|
3
|
+
const Ps = require('../utils/ps');
|
|
4
|
+
const Storage = require('../storage');
|
|
5
|
+
|
|
6
|
+
module.exports = {
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 创建
|
|
10
|
+
*/
|
|
11
|
+
create(config = {}) {
|
|
12
|
+
let opt = {};
|
|
13
|
+
|
|
14
|
+
if (Object.keys(config).length == 0) {
|
|
15
|
+
const defaultConfig = {
|
|
16
|
+
logger: {
|
|
17
|
+
type: 'application',
|
|
18
|
+
dir: Ps.getLogDir(),
|
|
19
|
+
encoding: 'utf8',
|
|
20
|
+
env: Ps.env(),
|
|
21
|
+
level: 'INFO',
|
|
22
|
+
consoleLevel: 'INFO',
|
|
23
|
+
disableConsoleAfterReady: !Ps.isDev(),
|
|
24
|
+
outputJSON: false,
|
|
25
|
+
buffer: true,
|
|
26
|
+
appLogName: `ee.log`,
|
|
27
|
+
coreLogName: 'ee-core.log',
|
|
28
|
+
agentLogName: 'ee-agent.log',
|
|
29
|
+
errorLogName: `ee-error.log`,
|
|
30
|
+
coreLogger: {},
|
|
31
|
+
allowDebugAtProd: false,
|
|
32
|
+
enablePerformanceTimer: false,
|
|
33
|
+
},
|
|
34
|
+
customLogger: {}
|
|
35
|
+
}
|
|
36
|
+
const sysConfig = this._getCoreDB().getItem('config');
|
|
37
|
+
opt = Object.assign(defaultConfig, {
|
|
38
|
+
logger: sysConfig.logger,
|
|
39
|
+
customLogger: sysConfig.customLogger || {}
|
|
40
|
+
});
|
|
41
|
+
} else {
|
|
42
|
+
opt.logger = config.logger;
|
|
43
|
+
opt.customLogger = config.customLogger;
|
|
44
|
+
}
|
|
45
|
+
//console.log('log---------', config);
|
|
46
|
+
|
|
47
|
+
assert(Object.keys(opt).length != 0, `logger config is null`);
|
|
48
|
+
|
|
49
|
+
const loggers = new Loggers(opt);
|
|
50
|
+
|
|
51
|
+
return loggers;
|
|
52
|
+
},
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 获取 coredb
|
|
56
|
+
*/
|
|
57
|
+
_getCoreDB() {
|
|
58
|
+
const coreDB = Storage.connection('system');
|
|
59
|
+
return coreDB;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
|
|
2
|
+
class IpcMain {
|
|
3
|
+
constructor() {
|
|
4
|
+
this.event = new EventEmitter();
|
|
5
|
+
this.services = {};
|
|
6
|
+
/* 根据name获取window id */
|
|
7
|
+
ipcMain.handle('MessageChannel.getIdFromName', (e, args) => {
|
|
8
|
+
return (this.services[args.name] || {}).id;
|
|
9
|
+
});
|
|
10
|
+
/* 使用name和window id注册一个服务 */
|
|
11
|
+
ipcMain.handle('MessageChannel.registryService', (e, args) => {
|
|
12
|
+
const { name, id } = args;
|
|
13
|
+
this.registry(name, id);
|
|
14
|
+
return this.services[name];
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* invoke [在主进程(main)中向另外一个服务进程(service)发送异步请求,并取得回调Promise]
|
|
21
|
+
* @param {[String]} name [服务名]
|
|
22
|
+
* @param {[String]} channel [服务监听的信号名]
|
|
23
|
+
* @param {[Any]} args [携带参数(会被序列化,不会传递对象Proptype信息)]
|
|
24
|
+
* @return {[Promise]} [回调]
|
|
25
|
+
*/
|
|
26
|
+
invoke (name, channel, args={}) {
|
|
27
|
+
const pid = getRandomString();
|
|
28
|
+
const { id } = this.services[name];
|
|
29
|
+
|
|
30
|
+
return new Promise((resolve, reject) => {
|
|
31
|
+
if (name === 'main') reject(new Error(`MessageChannel: the main process can not send a message to itself!`))
|
|
32
|
+
if (!id) reject(new Error(`MessageChannel: can not get the id of the window names ${name}`));
|
|
33
|
+
const win = BrowserWindow.fromId(id);
|
|
34
|
+
if (!win) reject(new Error(`MessageChannel: can not find a window with id: ${id}`));
|
|
35
|
+
win.webContents.send(channel, Object.assign(args, { pid, isFromMain: true }));
|
|
36
|
+
ipcMain.once(pid, function(event, rsp) {
|
|
37
|
+
resolve(rsp);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* handle [在主进程中(main)监听来自其它渲染进程(service/window)的请求,将promiseFunc执行的结果返回]
|
|
45
|
+
* @param {[String]} channel [服务监听的信号名]
|
|
46
|
+
* @param {[Function]} promiseFunc [此函数执行的结果会被发送到消息发送者]
|
|
47
|
+
* @return {[Promise]} [回调]
|
|
48
|
+
*/
|
|
49
|
+
handle(channel, promiseFunc) {
|
|
50
|
+
if (!promiseFunc instanceof Function) throw new Error('MessageChannel: promiseFunc must be a function!');
|
|
51
|
+
ipcMain.handle(channel, (event, ...args) => {
|
|
52
|
+
return promiseFunc(event, ...args).then((result) => {
|
|
53
|
+
|
|
54
|
+
return result;
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* handle [在主进程中(main)监听一次来自其它渲染进程(service/window)的请求,将promiseFunc执行的结果返回]
|
|
61
|
+
* @param {[String]} channel [服务监听的信号名]
|
|
62
|
+
* @param {[Function]} promiseFunc [此函数执行的结果会被发送到消息发送者]
|
|
63
|
+
* @return {[Promise]} [回调]
|
|
64
|
+
*/
|
|
65
|
+
handleOnce(channel, promiseFunc) {
|
|
66
|
+
if (!promiseFunc instanceof Function) throw new Error('MessageChannel: promiseFunc must be a function!');
|
|
67
|
+
ipcMain.handleOnce(channel, (event, ...args) => {
|
|
68
|
+
return promiseFunc(event, ...args).then(result => {
|
|
69
|
+
|
|
70
|
+
return result;
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* send [在主进程(main)向另外一个服务进程(service)发送异步请求,不可立即取得值,请配合on监听信号使用]
|
|
77
|
+
* @param {[String]} name [服务名]
|
|
78
|
+
* @param {[String]} channel [服务监听的信号名]
|
|
79
|
+
* @param {[Any]} args [携带参数(会被序列化,不会传递对象Proptype信息)]
|
|
80
|
+
*/
|
|
81
|
+
send(name, channel, args={}) {
|
|
82
|
+
const id = (this.services[name] || {}).id;
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
if (!id) throw new Error(`MessageChannel: can not get the id of the window names ${name}`);
|
|
86
|
+
const win = BrowserWindow.fromId(id);
|
|
87
|
+
if (!win) throw new Error(`MessageChannel: can not find a window with id: ${id}`);
|
|
88
|
+
|
|
89
|
+
win.webContents.send(channel, args);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* send [在主进程中(main)向指定某个id的渲染进程窗口(service/window)发送请求,不可立即取得值,请配合on监听信号使用]
|
|
94
|
+
* @param {[String]} id [window id]
|
|
95
|
+
* @param {[String]} channel [服务监听的信号名]
|
|
96
|
+
* @param {[Any]} args [携带参数(会被序列化,不会传递对象Proptype信息)]
|
|
97
|
+
*/
|
|
98
|
+
sendTo(id, channel, args) {
|
|
99
|
+
|
|
100
|
+
if (!BrowserWindow.fromId(id)) throw new Error(`MessageChannel: can not find a window with id:${id}!`);
|
|
101
|
+
BrowserWindow.fromId(id).webContents.send(channel, args);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* on [在主进程中(main)监听来自其它渲染进程(service/window)的请求]
|
|
106
|
+
* @param {[String]} channel [服务监听的信号名]
|
|
107
|
+
* @param {[Function]} func [消息到达后,此函数会被触发,同于原生ipcRenderer.on]
|
|
108
|
+
*/
|
|
109
|
+
on(channel, func) {
|
|
110
|
+
if (!func instanceof Function) throw new Error('MessageChannel: func must be a function!');
|
|
111
|
+
ipcMain.on(channel, (event, ...args) => {
|
|
112
|
+
|
|
113
|
+
func(event, ...args);
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* once [在主进程中(main)监听一次来自其它渲染进程(service/window)的请求]
|
|
119
|
+
* @param {[String]} channel [服务监听的信号名]
|
|
120
|
+
* @param {[Function]} func [消息到达后,此函数会被触发,同于原生ipcRenderer.on]
|
|
121
|
+
*/
|
|
122
|
+
once(channel, func) {
|
|
123
|
+
if (!func instanceof Function) throw new Error('MessageChannel: func must be a function!');
|
|
124
|
+
ipcMain.once(channel, (event, ...args) => {
|
|
125
|
+
|
|
126
|
+
func(event, ...args);
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* registry [注册BrowserWindow和BrowserService]
|
|
132
|
+
* @param {[String]} name [唯一的名字]
|
|
133
|
+
* @param {[String]} id [window id]
|
|
134
|
+
* @param {[String]} pid [process id]
|
|
135
|
+
*/
|
|
136
|
+
registry(name, id, pid) {
|
|
137
|
+
if (name === 'main') throw new Error(`MessageChannel: you can not registry a service named:${name}, it's reserved for the main process!`)
|
|
138
|
+
if (this.services[name]) console.warn(`MessageChannel: the service - ${name} has been registeried!`)
|
|
139
|
+
this.services[name] = { name, id, pid };
|
|
140
|
+
this.event.emit('registry', this.services[name]);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* unregistry [注册BrowserWindow和BrowserService]
|
|
145
|
+
* @param {[String]} name [唯一的名字]
|
|
146
|
+
* @param {[String]} id [window id]
|
|
147
|
+
* @param {[String]} pid [process id]
|
|
148
|
+
*/
|
|
149
|
+
unregistry(name) {
|
|
150
|
+
if (name === 'main') throw new Error(`MessageChannel: you can not unregistry a service named:${name}, it's reserved for the main process!`);
|
|
151
|
+
if (this.services[name]) console.warn(`MessageChannel: the service - ${name} will be unregisteried!`);
|
|
152
|
+
if (this.services[name]) {
|
|
153
|
+
this.event.emit('unregistry', this.services[name]);
|
|
154
|
+
delete this.services[name];
|
|
155
|
+
} else {
|
|
156
|
+
console.warn(`MessageChannel: unregistry -> the service - ${name} is not found!`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
File without changes
|
|
@@ -1,143 +1,143 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
const assert = require('assert');
|
|
4
|
-
const is = require('is-type-of');
|
|
5
|
-
const Koa = require('koa');
|
|
6
|
-
const cors = require('koa2-cors');
|
|
7
|
-
const koaBody = require('koa-body');
|
|
8
|
-
const https = require('https');
|
|
9
|
-
const fs = require('fs');
|
|
10
|
-
const path = require('path');
|
|
11
|
-
const _ = require('lodash');
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* http server
|
|
15
|
-
*/
|
|
16
|
-
class HttpServer {
|
|
17
|
-
constructor (app) {
|
|
18
|
-
this.app = app;
|
|
19
|
-
this.options = this.app.config.httpServer;
|
|
20
|
-
|
|
21
|
-
if (!this.options.enable) {
|
|
22
|
-
return;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
let port = process.env.EE_HTTP_PORT ? parseInt(process.env.EE_HTTP_PORT) : parseInt(this.getHttpPort());
|
|
26
|
-
assert(typeof port === 'number', 'http port required, and must be a number');
|
|
27
|
-
|
|
28
|
-
this.create();
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* 创建服务
|
|
33
|
-
*/
|
|
34
|
-
create () {
|
|
35
|
-
const self = this;
|
|
36
|
-
const httpServer = this.options;
|
|
37
|
-
const isHttps = httpServer?.https?.enable ?? false;
|
|
38
|
-
let sslOptions = {};
|
|
39
|
-
|
|
40
|
-
if (isHttps === true) {
|
|
41
|
-
httpServer.protocol = 'https://';
|
|
42
|
-
const keyFile = path.join(this.app.config.homeDir, httpServer.https.key);
|
|
43
|
-
const certFile = path.join(this.app.config.homeDir, httpServer.https.cert);
|
|
44
|
-
assert(fs.existsSync(keyFile), 'ssl key file is required');
|
|
45
|
-
assert(fs.existsSync(certFile), 'ssl cert file is required');
|
|
46
|
-
|
|
47
|
-
sslOptions.key = fs.readFileSync(keyFile);
|
|
48
|
-
sslOptions.cert = fs.readFileSync(certFile);
|
|
49
|
-
}
|
|
50
|
-
const url = httpServer.protocol + httpServer.host + ':' + httpServer.port;
|
|
51
|
-
const corsOptions = httpServer.cors;
|
|
52
|
-
|
|
53
|
-
const koaApp = new Koa();
|
|
54
|
-
koaApp
|
|
55
|
-
.use(cors(corsOptions))
|
|
56
|
-
.use(koaBody(httpServer.body))
|
|
57
|
-
.use(async (ctx, next) => {
|
|
58
|
-
ctx.eeApp = self.app;
|
|
59
|
-
await next();
|
|
60
|
-
})
|
|
61
|
-
.use(this.dispatch);
|
|
62
|
-
|
|
63
|
-
let msg = '[ee-core:http:server] server is: ' + url;
|
|
64
|
-
if (isHttps) {
|
|
65
|
-
https.createServer(sslOptions, koaApp.callback()).listen(httpServer.port, (err) => {
|
|
66
|
-
msg = err ? err : msg;
|
|
67
|
-
self.app.coreLogger.info(msg);
|
|
68
|
-
});
|
|
69
|
-
} else {
|
|
70
|
-
koaApp.listen(httpServer.port, (e) => {
|
|
71
|
-
msg = e ? e : msg;
|
|
72
|
-
self.app.coreLogger.info(msg);
|
|
73
|
-
});
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* 路由分发
|
|
79
|
-
*/
|
|
80
|
-
async dispatch (ctx, next) {
|
|
81
|
-
const config = ctx.eeApp.config.httpServer;
|
|
82
|
-
let uriPath = ctx.request.path;
|
|
83
|
-
const method = ctx.request.method;
|
|
84
|
-
let params = ctx.request.query;
|
|
85
|
-
params = is.object(params) ? JSON.parse(JSON.stringify(params)) : {};
|
|
86
|
-
const body = ctx.request.body;
|
|
87
|
-
|
|
88
|
-
// 默认
|
|
89
|
-
ctx.response.status = 200;
|
|
90
|
-
|
|
91
|
-
// 添加到全局属性
|
|
92
|
-
ctx.eeApp.request = ctx.request;
|
|
93
|
-
ctx.eeApp.response = ctx.response;
|
|
94
|
-
|
|
95
|
-
try {
|
|
96
|
-
// 找函数
|
|
97
|
-
// 去除开头的 '/'
|
|
98
|
-
if (uriPath.indexOf('/') == 0) {
|
|
99
|
-
uriPath = uriPath.substring(1);
|
|
100
|
-
}
|
|
101
|
-
// 过滤
|
|
102
|
-
if (_.includes(config.filterRequest.uris, uriPath)) {
|
|
103
|
-
ctx.response.body = config.filterRequest.returnData;
|
|
104
|
-
await next();
|
|
105
|
-
return
|
|
106
|
-
}
|
|
107
|
-
if (uriPath.slice(0, 10) != 'controller') {
|
|
108
|
-
uriPath = 'controller/' + uriPath;
|
|
109
|
-
}
|
|
110
|
-
const cmd = uriPath.split('/').join('.');
|
|
111
|
-
const args = (method == 'POST') ? body : params;
|
|
112
|
-
let fn = null;
|
|
113
|
-
if (is.string(cmd)) {
|
|
114
|
-
const actions = cmd.split('.');
|
|
115
|
-
let obj = ctx.eeApp;
|
|
116
|
-
actions.forEach(key => {
|
|
117
|
-
obj = obj[key];
|
|
118
|
-
if (!obj) throw new Error(`class or function '${key}' not exists`);
|
|
119
|
-
});
|
|
120
|
-
fn = obj;
|
|
121
|
-
}
|
|
122
|
-
if (!fn) throw new Error('function not exists');
|
|
123
|
-
|
|
124
|
-
const result = await fn.call(ctx.eeApp, args);
|
|
125
|
-
ctx.response.body = result;
|
|
126
|
-
} catch (err) {
|
|
127
|
-
ctx.eeApp.console.error('[ee-core:http:server] throw error:', err);
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
await next();
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* 获取http端口
|
|
135
|
-
*/
|
|
136
|
-
getHttpPort () {
|
|
137
|
-
const cdb = this.getCoreDB();
|
|
138
|
-
const port = cdb.getItem('config').httpServer.port;
|
|
139
|
-
return parseInt(port);
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const assert = require('assert');
|
|
4
|
+
const is = require('is-type-of');
|
|
5
|
+
const Koa = require('koa');
|
|
6
|
+
const cors = require('koa2-cors');
|
|
7
|
+
const koaBody = require('koa-body');
|
|
8
|
+
const https = require('https');
|
|
9
|
+
const fs = require('fs');
|
|
10
|
+
const path = require('path');
|
|
11
|
+
const _ = require('lodash');
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* http server
|
|
15
|
+
*/
|
|
16
|
+
class HttpServer {
|
|
17
|
+
constructor (app) {
|
|
18
|
+
this.app = app;
|
|
19
|
+
this.options = this.app.config.httpServer;
|
|
20
|
+
|
|
21
|
+
if (!this.options.enable) {
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
let port = process.env.EE_HTTP_PORT ? parseInt(process.env.EE_HTTP_PORT) : parseInt(this.getHttpPort());
|
|
26
|
+
assert(typeof port === 'number', 'http port required, and must be a number');
|
|
27
|
+
|
|
28
|
+
this.create();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 创建服务
|
|
33
|
+
*/
|
|
34
|
+
create () {
|
|
35
|
+
const self = this;
|
|
36
|
+
const httpServer = this.options;
|
|
37
|
+
const isHttps = httpServer?.https?.enable ?? false;
|
|
38
|
+
let sslOptions = {};
|
|
39
|
+
|
|
40
|
+
if (isHttps === true) {
|
|
41
|
+
httpServer.protocol = 'https://';
|
|
42
|
+
const keyFile = path.join(this.app.config.homeDir, httpServer.https.key);
|
|
43
|
+
const certFile = path.join(this.app.config.homeDir, httpServer.https.cert);
|
|
44
|
+
assert(fs.existsSync(keyFile), 'ssl key file is required');
|
|
45
|
+
assert(fs.existsSync(certFile), 'ssl cert file is required');
|
|
46
|
+
|
|
47
|
+
sslOptions.key = fs.readFileSync(keyFile);
|
|
48
|
+
sslOptions.cert = fs.readFileSync(certFile);
|
|
49
|
+
}
|
|
50
|
+
const url = httpServer.protocol + httpServer.host + ':' + httpServer.port;
|
|
51
|
+
const corsOptions = httpServer.cors;
|
|
52
|
+
|
|
53
|
+
const koaApp = new Koa();
|
|
54
|
+
koaApp
|
|
55
|
+
.use(cors(corsOptions))
|
|
56
|
+
.use(koaBody(httpServer.body))
|
|
57
|
+
.use(async (ctx, next) => {
|
|
58
|
+
ctx.eeApp = self.app;
|
|
59
|
+
await next();
|
|
60
|
+
})
|
|
61
|
+
.use(this.dispatch);
|
|
62
|
+
|
|
63
|
+
let msg = '[ee-core:http:server] server is: ' + url;
|
|
64
|
+
if (isHttps) {
|
|
65
|
+
https.createServer(sslOptions, koaApp.callback()).listen(httpServer.port, (err) => {
|
|
66
|
+
msg = err ? err : msg;
|
|
67
|
+
self.app.coreLogger.info(msg);
|
|
68
|
+
});
|
|
69
|
+
} else {
|
|
70
|
+
koaApp.listen(httpServer.port, (e) => {
|
|
71
|
+
msg = e ? e : msg;
|
|
72
|
+
self.app.coreLogger.info(msg);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 路由分发
|
|
79
|
+
*/
|
|
80
|
+
async dispatch (ctx, next) {
|
|
81
|
+
const config = ctx.eeApp.config.httpServer;
|
|
82
|
+
let uriPath = ctx.request.path;
|
|
83
|
+
const method = ctx.request.method;
|
|
84
|
+
let params = ctx.request.query;
|
|
85
|
+
params = is.object(params) ? JSON.parse(JSON.stringify(params)) : {};
|
|
86
|
+
const body = ctx.request.body;
|
|
87
|
+
|
|
88
|
+
// 默认
|
|
89
|
+
ctx.response.status = 200;
|
|
90
|
+
|
|
91
|
+
// 添加到全局属性
|
|
92
|
+
ctx.eeApp.request = ctx.request;
|
|
93
|
+
ctx.eeApp.response = ctx.response;
|
|
94
|
+
|
|
95
|
+
try {
|
|
96
|
+
// 找函数
|
|
97
|
+
// 去除开头的 '/'
|
|
98
|
+
if (uriPath.indexOf('/') == 0) {
|
|
99
|
+
uriPath = uriPath.substring(1);
|
|
100
|
+
}
|
|
101
|
+
// 过滤
|
|
102
|
+
if (_.includes(config.filterRequest.uris, uriPath)) {
|
|
103
|
+
ctx.response.body = config.filterRequest.returnData;
|
|
104
|
+
await next();
|
|
105
|
+
return
|
|
106
|
+
}
|
|
107
|
+
if (uriPath.slice(0, 10) != 'controller') {
|
|
108
|
+
uriPath = 'controller/' + uriPath;
|
|
109
|
+
}
|
|
110
|
+
const cmd = uriPath.split('/').join('.');
|
|
111
|
+
const args = (method == 'POST') ? body : params;
|
|
112
|
+
let fn = null;
|
|
113
|
+
if (is.string(cmd)) {
|
|
114
|
+
const actions = cmd.split('.');
|
|
115
|
+
let obj = ctx.eeApp;
|
|
116
|
+
actions.forEach(key => {
|
|
117
|
+
obj = obj[key];
|
|
118
|
+
if (!obj) throw new Error(`class or function '${key}' not exists`);
|
|
119
|
+
});
|
|
120
|
+
fn = obj;
|
|
121
|
+
}
|
|
122
|
+
if (!fn) throw new Error('function not exists');
|
|
123
|
+
|
|
124
|
+
const result = await fn.call(ctx.eeApp, args);
|
|
125
|
+
ctx.response.body = result;
|
|
126
|
+
} catch (err) {
|
|
127
|
+
ctx.eeApp.console.error('[ee-core:http:server] throw error:', err);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
await next();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* 获取http端口
|
|
135
|
+
*/
|
|
136
|
+
getHttpPort () {
|
|
137
|
+
const cdb = this.getCoreDB();
|
|
138
|
+
const port = cdb.getItem('config').httpServer.port;
|
|
139
|
+
return parseInt(port);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
143
|
module.exports = HttpServer;
|