oox 0.3.7 → 0.3.8
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/bin/starter.js +1 -1
- package/modules/index.js +1 -1
- package/package.json +2 -1
- package/types/modules/index.d.ts +1 -1
- package/modules/http/index.js +0 -278
- package/modules/http/router.js +0 -210
- package/modules/http/utils.js +0 -75
- package/types/modules/http/index.d.ts +0 -63
- package/types/modules/http/router.d.ts +0 -49
- package/types/modules/http/utils.d.ts +0 -14
package/bin/starter.js
CHANGED
|
@@ -56,8 +56,8 @@ export async function startup() {
|
|
|
56
56
|
await loadEntry(config.name, config.entryInfo.path);
|
|
57
57
|
// 服务启动
|
|
58
58
|
await oox.serve();
|
|
59
|
+
// 服务启动完成
|
|
59
60
|
oox.emit('app:served');
|
|
60
|
-
const { http } = oox.modules.builtins;
|
|
61
61
|
console.log();
|
|
62
62
|
console.log('Service', chalk.bold(`${oox.config.name}`), 'running.');
|
|
63
63
|
// 打包服务地址
|
package/modules/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "oox",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.8",
|
|
4
4
|
"description": "OOX Service Engine",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"http",
|
|
@@ -40,6 +40,7 @@
|
|
|
40
40
|
"homepage": "https://gitee.com/lipingruan/oox",
|
|
41
41
|
"license": "MIT",
|
|
42
42
|
"dependencies": {
|
|
43
|
+
"@oox/http": "^1.0.0",
|
|
43
44
|
"chalk": "^5.6.2"
|
|
44
45
|
},
|
|
45
46
|
"engines": {
|
package/types/modules/index.d.ts
CHANGED
package/modules/http/index.js
DELETED
|
@@ -1,278 +0,0 @@
|
|
|
1
|
-
import * as http from 'node:http';
|
|
2
|
-
import * as https from 'node:https';
|
|
3
|
-
import { parseHTTPBody } from './utils.js';
|
|
4
|
-
import Router from './router.js';
|
|
5
|
-
import * as oox from '../../index.js';
|
|
6
|
-
import { Module } from '../module.js';
|
|
7
|
-
export class HTTPConfig {
|
|
8
|
-
enabled = true;
|
|
9
|
-
// listen port
|
|
10
|
-
port = 0;
|
|
11
|
-
// service path
|
|
12
|
-
path = '/';
|
|
13
|
-
// browser cross origin
|
|
14
|
-
origin = '';
|
|
15
|
-
// https options
|
|
16
|
-
ssl = {
|
|
17
|
-
// enable https
|
|
18
|
-
enabled: false,
|
|
19
|
-
// ssl certificate path
|
|
20
|
-
cert: '',
|
|
21
|
-
// ssl private key path
|
|
22
|
-
key: '',
|
|
23
|
-
// ssl ca path
|
|
24
|
-
ca: ''
|
|
25
|
-
};
|
|
26
|
-
}
|
|
27
|
-
export default class HTTPModule extends Module {
|
|
28
|
-
name = 'http';
|
|
29
|
-
config = new HTTPConfig;
|
|
30
|
-
server = null;
|
|
31
|
-
router = new Router();
|
|
32
|
-
getURL() {
|
|
33
|
-
const { host } = oox.config;
|
|
34
|
-
const { port, path } = this.config;
|
|
35
|
-
const protocol = this.config.ssl.enabled ? `https:` : `http:`;
|
|
36
|
-
return new URL(`${protocol}//${host}:${port}${path}`);
|
|
37
|
-
}
|
|
38
|
-
// 注册GET路由
|
|
39
|
-
get(path, ...args) {
|
|
40
|
-
this.router.get(path, ...args);
|
|
41
|
-
return this;
|
|
42
|
-
}
|
|
43
|
-
// 注册POST路由
|
|
44
|
-
post(path, ...args) {
|
|
45
|
-
this.router.post(path, ...args);
|
|
46
|
-
return this;
|
|
47
|
-
}
|
|
48
|
-
// 注册PUT路由
|
|
49
|
-
put(path, ...args) {
|
|
50
|
-
this.router.put(path, ...args);
|
|
51
|
-
return this;
|
|
52
|
-
}
|
|
53
|
-
// 注册DELETE路由
|
|
54
|
-
delete(path, ...args) {
|
|
55
|
-
this.router.delete(path, ...args);
|
|
56
|
-
return this;
|
|
57
|
-
}
|
|
58
|
-
// 注册全局中间件
|
|
59
|
-
use(middleware) {
|
|
60
|
-
this.router.use(middleware);
|
|
61
|
-
return this;
|
|
62
|
-
}
|
|
63
|
-
setConfig(config) {
|
|
64
|
-
Object.assign(this.config, config);
|
|
65
|
-
if (!config.hasOwnProperty('port')) {
|
|
66
|
-
this.config.port = oox.config.port;
|
|
67
|
-
}
|
|
68
|
-
if (!config.hasOwnProperty('origin')) {
|
|
69
|
-
this.config.origin = oox.config.origin;
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
getConfig() {
|
|
73
|
-
return this.config;
|
|
74
|
-
}
|
|
75
|
-
get serviceURL() {
|
|
76
|
-
return this.getURL();
|
|
77
|
-
}
|
|
78
|
-
/**
|
|
79
|
-
* start http service
|
|
80
|
-
*/
|
|
81
|
-
async serve() {
|
|
82
|
-
await this.stop();
|
|
83
|
-
const { port, ssl } = this.config;
|
|
84
|
-
if (ssl.enabled) {
|
|
85
|
-
const fs = await import('node:fs');
|
|
86
|
-
const options = {
|
|
87
|
-
key: ssl.key ? fs.readFileSync(ssl.key) : undefined,
|
|
88
|
-
cert: ssl.cert ? fs.readFileSync(ssl.cert) : undefined,
|
|
89
|
-
ca: ssl.ca ? fs.readFileSync(ssl.ca) : undefined
|
|
90
|
-
};
|
|
91
|
-
if (!options.key || !options.cert) {
|
|
92
|
-
throw new Error('HTTPS enabled but missing key or cert');
|
|
93
|
-
}
|
|
94
|
-
this.server = https.createServer(options, this.requestHandler.bind(this));
|
|
95
|
-
}
|
|
96
|
-
else {
|
|
97
|
-
this.server = http.createServer(this.requestHandler.bind(this));
|
|
98
|
-
}
|
|
99
|
-
this.server.listen(port);
|
|
100
|
-
const address = this.server.address();
|
|
101
|
-
if (!address || 'object' !== typeof address)
|
|
102
|
-
throw new Error('Cannot read http server port');
|
|
103
|
-
this.config.port = address.port;
|
|
104
|
-
}
|
|
105
|
-
/**
|
|
106
|
-
* stop http service
|
|
107
|
-
*/
|
|
108
|
-
async stop() {
|
|
109
|
-
const { server } = this;
|
|
110
|
-
if (!server || !server.listening)
|
|
111
|
-
return Promise.resolve();
|
|
112
|
-
return new Promise((resolve, reject) => {
|
|
113
|
-
server.close(function (error) {
|
|
114
|
-
if (error)
|
|
115
|
-
reject(error);
|
|
116
|
-
else
|
|
117
|
-
resolve();
|
|
118
|
-
});
|
|
119
|
-
});
|
|
120
|
-
}
|
|
121
|
-
/**
|
|
122
|
-
* browser cross origin
|
|
123
|
-
*/
|
|
124
|
-
cors(request, response) {
|
|
125
|
-
// origin checking
|
|
126
|
-
const origin = this.config.origin;
|
|
127
|
-
const requestOrigin = request.headers.origin;
|
|
128
|
-
if (origin && requestOrigin) {
|
|
129
|
-
let allow = false;
|
|
130
|
-
if ('string' === typeof origin) {
|
|
131
|
-
allow = origin === '*' || new RegExp(origin).test(requestOrigin);
|
|
132
|
-
}
|
|
133
|
-
else if (Array.isArray(origin)) {
|
|
134
|
-
allow = origin.some(item => item === '*' || new RegExp(item).test(requestOrigin));
|
|
135
|
-
}
|
|
136
|
-
if (allow) {
|
|
137
|
-
response.setHeader('Access-Control-Allow-Origin', requestOrigin);
|
|
138
|
-
response.setHeader('Vary', 'Origin');
|
|
139
|
-
}
|
|
140
|
-
else {
|
|
141
|
-
response.statusCode = 403;
|
|
142
|
-
response.end();
|
|
143
|
-
return false;
|
|
144
|
-
}
|
|
145
|
-
response.setHeader('Access-Control-Max-Age', 3600);
|
|
146
|
-
response.setHeader('Access-Control-Allow-Headers', 'x-caller,x-token,content-type');
|
|
147
|
-
response.setHeader('Access-Control-Allow-Methods', '*');
|
|
148
|
-
}
|
|
149
|
-
if (request.method === 'OPTIONS') {
|
|
150
|
-
response.statusCode = 204;
|
|
151
|
-
response.end();
|
|
152
|
-
return false;
|
|
153
|
-
}
|
|
154
|
-
return true;
|
|
155
|
-
}
|
|
156
|
-
async requestHandler(request, response) {
|
|
157
|
-
const url = new URL(request.url || '', `http://${request.headers.host || 'localhost'}`);
|
|
158
|
-
const method = request.method || 'GET';
|
|
159
|
-
// 尝试匹配路由
|
|
160
|
-
const matched = this.router.match(method, url.pathname);
|
|
161
|
-
if (matched) {
|
|
162
|
-
const req = this.router.createRequestObject(request, url);
|
|
163
|
-
const res = this.router.createResponseObject(response);
|
|
164
|
-
// 解析请求体
|
|
165
|
-
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
166
|
-
try {
|
|
167
|
-
req.body = await parseHTTPBody(request);
|
|
168
|
-
}
|
|
169
|
-
catch (error) {
|
|
170
|
-
return this.respond(request, response, {
|
|
171
|
-
success: false,
|
|
172
|
-
error: {
|
|
173
|
-
message: error.message,
|
|
174
|
-
stack: error.stack
|
|
175
|
-
}
|
|
176
|
-
});
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
await this.router.handleRoute(matched.route, matched.params, req, res);
|
|
180
|
-
return;
|
|
181
|
-
}
|
|
182
|
-
// 内置cors仅处理RPC请求
|
|
183
|
-
if (!this.cors(request, response))
|
|
184
|
-
return;
|
|
185
|
-
// 回退到RPC调用
|
|
186
|
-
if (url.pathname === this.config.path) {
|
|
187
|
-
await this.call(request, response);
|
|
188
|
-
}
|
|
189
|
-
else {
|
|
190
|
-
const error = new Error('Invalid URL');
|
|
191
|
-
return this.respond(request, response, {
|
|
192
|
-
success: false,
|
|
193
|
-
error: {
|
|
194
|
-
message: error.message,
|
|
195
|
-
stack: error.stack
|
|
196
|
-
}
|
|
197
|
-
});
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
/**
|
|
201
|
-
* 从请求里获取调用的接口和参数
|
|
202
|
-
*/
|
|
203
|
-
async getCallArgsFromRequest(request) {
|
|
204
|
-
const args = await parseHTTPBody(request);
|
|
205
|
-
if (!args || 'object' !== typeof args || !args.action)
|
|
206
|
-
throw new Error('Content Invalid');
|
|
207
|
-
else
|
|
208
|
-
return args;
|
|
209
|
-
}
|
|
210
|
-
/**
|
|
211
|
-
* HTTP-RPC服务器请求监听方法
|
|
212
|
-
*/
|
|
213
|
-
async call(request, response) {
|
|
214
|
-
// global unique id
|
|
215
|
-
const traceId = String(request.headers['x-trace-id'] || '');
|
|
216
|
-
// service name, required
|
|
217
|
-
const caller = String(request.headers['x-caller'] || 'anonymous');
|
|
218
|
-
// client ip or caller service ip
|
|
219
|
-
const ip = String(request.headers['x-real-ip'] || request.socket.remoteAddress || '');
|
|
220
|
-
// startup client ip
|
|
221
|
-
const sourceIP = String(request.headers['x-source-ip'] || request.socket.remoteAddress || '');
|
|
222
|
-
// check token
|
|
223
|
-
const token = String(request.headers['x-token'] || '');
|
|
224
|
-
const { allow, reason } = oox.checkAllow(ip, caller, token);
|
|
225
|
-
if (!allow)
|
|
226
|
-
return this.respond(request, response, {
|
|
227
|
-
success: false,
|
|
228
|
-
error: {
|
|
229
|
-
message: reason
|
|
230
|
-
}
|
|
231
|
-
});
|
|
232
|
-
let callArgs = Object.create(null);
|
|
233
|
-
try {
|
|
234
|
-
callArgs = await this.getCallArgsFromRequest(request);
|
|
235
|
-
}
|
|
236
|
-
catch (error) {
|
|
237
|
-
return this.respond(request, response, {
|
|
238
|
-
success: false,
|
|
239
|
-
error: {
|
|
240
|
-
message: error.message,
|
|
241
|
-
stack: error.stack
|
|
242
|
-
}
|
|
243
|
-
});
|
|
244
|
-
}
|
|
245
|
-
const { action, params = [] } = callArgs;
|
|
246
|
-
const context = oox.genContext({ traceId, caller, sourceIP, ip, callerId: '' });
|
|
247
|
-
const format = await oox.call(action, params, context);
|
|
248
|
-
this.respond(request, response, format);
|
|
249
|
-
}
|
|
250
|
-
/**
|
|
251
|
-
* HTTP Response Catch
|
|
252
|
-
*/
|
|
253
|
-
respond(_request, response, returns) {
|
|
254
|
-
let returnsString = '';
|
|
255
|
-
if (!oox.config.errorStack && returns.error) {
|
|
256
|
-
// 不返回错误调用栈信息
|
|
257
|
-
delete returns.error.stack;
|
|
258
|
-
}
|
|
259
|
-
try {
|
|
260
|
-
returnsString = JSON.stringify(returns);
|
|
261
|
-
}
|
|
262
|
-
catch (error) {
|
|
263
|
-
delete returns.body;
|
|
264
|
-
returns.success = false;
|
|
265
|
-
returns.error = {
|
|
266
|
-
message: error.message
|
|
267
|
-
};
|
|
268
|
-
if (oox.config.errorStack) {
|
|
269
|
-
// 返回错误调用栈信息
|
|
270
|
-
returns.error.stack = error.stack;
|
|
271
|
-
}
|
|
272
|
-
returnsString = JSON.stringify(returns);
|
|
273
|
-
}
|
|
274
|
-
response.setHeader('Content-Type', 'application/json');
|
|
275
|
-
response.setHeader('Content-Length', Buffer.byteLength(returnsString));
|
|
276
|
-
response.end(returnsString);
|
|
277
|
-
}
|
|
278
|
-
}
|
package/modules/http/router.js
DELETED
|
@@ -1,210 +0,0 @@
|
|
|
1
|
-
export default class Router {
|
|
2
|
-
routes = new Map();
|
|
3
|
-
globalMiddleware = [];
|
|
4
|
-
// 注册GET路由
|
|
5
|
-
get(path, ...args) {
|
|
6
|
-
const { handler, middleware } = this.parseRouteArgs(args);
|
|
7
|
-
this.addRoute('GET', path, handler, middleware);
|
|
8
|
-
}
|
|
9
|
-
// 注册POST路由
|
|
10
|
-
post(path, ...args) {
|
|
11
|
-
const { handler, middleware } = this.parseRouteArgs(args);
|
|
12
|
-
this.addRoute('POST', path, handler, middleware);
|
|
13
|
-
}
|
|
14
|
-
// 注册PUT路由
|
|
15
|
-
put(path, ...args) {
|
|
16
|
-
const { handler, middleware } = this.parseRouteArgs(args);
|
|
17
|
-
this.addRoute('PUT', path, handler, middleware);
|
|
18
|
-
}
|
|
19
|
-
// 注册DELETE路由
|
|
20
|
-
delete(path, ...args) {
|
|
21
|
-
const { handler, middleware } = this.parseRouteArgs(args);
|
|
22
|
-
this.addRoute('DELETE', path, handler, middleware);
|
|
23
|
-
}
|
|
24
|
-
// 解析路由参数,支持多种传入方式
|
|
25
|
-
parseRouteArgs(args) {
|
|
26
|
-
let handler;
|
|
27
|
-
let middleware = [];
|
|
28
|
-
if (args.length === 0) {
|
|
29
|
-
throw new Error('No handler provided for route');
|
|
30
|
-
}
|
|
31
|
-
// 方式1: [handler] 或 [middlewareArray, handler]
|
|
32
|
-
if (args.length === 1) {
|
|
33
|
-
if (typeof args[0] === 'function') {
|
|
34
|
-
handler = args[0];
|
|
35
|
-
}
|
|
36
|
-
else {
|
|
37
|
-
throw new Error('Invalid route handler');
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
// 方式2: [handler, middlewareArray] 或 [middleware1, middleware2, handler] 或 [middlewareArray, handler]
|
|
41
|
-
else {
|
|
42
|
-
// 检查最后一个参数是否是函数(处理器)
|
|
43
|
-
if (typeof args[args.length - 1] === 'function') {
|
|
44
|
-
handler = args[args.length - 1];
|
|
45
|
-
// 前面的所有都是中间件
|
|
46
|
-
const middleArgs = args.slice(0, -1);
|
|
47
|
-
// 展平中间件数组
|
|
48
|
-
for (const arg of middleArgs) {
|
|
49
|
-
if (Array.isArray(arg)) {
|
|
50
|
-
middleware.push(...arg);
|
|
51
|
-
}
|
|
52
|
-
else if (typeof arg === 'function') {
|
|
53
|
-
middleware.push(arg);
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
// 检查第一个参数是否是函数
|
|
58
|
-
else if (typeof args[0] === 'function') {
|
|
59
|
-
handler = args[0];
|
|
60
|
-
// 后面的是中间件
|
|
61
|
-
const middleArgs = args.slice(1);
|
|
62
|
-
for (const arg of middleArgs) {
|
|
63
|
-
if (Array.isArray(arg)) {
|
|
64
|
-
middleware.push(...arg);
|
|
65
|
-
}
|
|
66
|
-
else if (typeof arg === 'function') {
|
|
67
|
-
middleware.push(arg);
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
else {
|
|
72
|
-
throw new Error('Invalid route arguments');
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
return { handler, middleware };
|
|
76
|
-
}
|
|
77
|
-
// 注册全局中间件
|
|
78
|
-
use(middleware) {
|
|
79
|
-
this.globalMiddleware.push(middleware);
|
|
80
|
-
}
|
|
81
|
-
// 注册特定路径的中间件
|
|
82
|
-
usePath(path, middleware) {
|
|
83
|
-
// 实现路径级中间件
|
|
84
|
-
}
|
|
85
|
-
// 添加路由
|
|
86
|
-
addRoute(method, path, handler, middleware = []) {
|
|
87
|
-
// 编译路径为正则表达式,支持路径参数
|
|
88
|
-
const { regex, paramNames } = this.compilePath(path);
|
|
89
|
-
let routes = [];
|
|
90
|
-
if (this.routes.has(method)) {
|
|
91
|
-
routes = this.routes.get(method) || [];
|
|
92
|
-
}
|
|
93
|
-
else {
|
|
94
|
-
routes = [];
|
|
95
|
-
this.routes.set(method, routes);
|
|
96
|
-
}
|
|
97
|
-
routes.push({
|
|
98
|
-
path,
|
|
99
|
-
method,
|
|
100
|
-
handler,
|
|
101
|
-
middleware,
|
|
102
|
-
regex,
|
|
103
|
-
paramNames
|
|
104
|
-
});
|
|
105
|
-
}
|
|
106
|
-
// 编译路径为正则表达式
|
|
107
|
-
compilePath(path) {
|
|
108
|
-
const paramNames = [];
|
|
109
|
-
const regexPattern = path
|
|
110
|
-
.replace(/:([^/]+)/g, (_, paramName) => {
|
|
111
|
-
paramNames.push(paramName);
|
|
112
|
-
return '([^/]+)';
|
|
113
|
-
})
|
|
114
|
-
.replace(/\//g, '\\/')
|
|
115
|
-
.replace(/\*/g, '.*');
|
|
116
|
-
return {
|
|
117
|
-
regex: new RegExp(`^${regexPattern}$`),
|
|
118
|
-
paramNames
|
|
119
|
-
};
|
|
120
|
-
}
|
|
121
|
-
// 匹配路由
|
|
122
|
-
match(method, path) {
|
|
123
|
-
const routes = this.routes.get(method) || [];
|
|
124
|
-
for (const route of routes) {
|
|
125
|
-
const match = path.match(route.regex);
|
|
126
|
-
if (match) {
|
|
127
|
-
const params = {};
|
|
128
|
-
route.paramNames.forEach((paramName, index) => {
|
|
129
|
-
params[paramName] = match[index + 1];
|
|
130
|
-
});
|
|
131
|
-
return { route, params };
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
return null;
|
|
135
|
-
}
|
|
136
|
-
// 创建请求对象
|
|
137
|
-
createRequestObject(originalRequest, url) {
|
|
138
|
-
return {
|
|
139
|
-
originalRequest,
|
|
140
|
-
url,
|
|
141
|
-
method: originalRequest.method || 'GET',
|
|
142
|
-
path: url.pathname,
|
|
143
|
-
query: Object.fromEntries(url.searchParams),
|
|
144
|
-
params: {},
|
|
145
|
-
headers: originalRequest.headers,
|
|
146
|
-
body: null
|
|
147
|
-
};
|
|
148
|
-
}
|
|
149
|
-
// 创建响应对象
|
|
150
|
-
createResponseObject(originalResponse) {
|
|
151
|
-
let statusCode = 200;
|
|
152
|
-
return {
|
|
153
|
-
originalResponse,
|
|
154
|
-
status(code) {
|
|
155
|
-
statusCode = code;
|
|
156
|
-
return this;
|
|
157
|
-
},
|
|
158
|
-
json(data) {
|
|
159
|
-
const jsonString = JSON.stringify(data);
|
|
160
|
-
this.originalResponse.statusCode = statusCode;
|
|
161
|
-
this.originalResponse.setHeader('Content-Type', 'application/json');
|
|
162
|
-
this.originalResponse.setHeader('Content-Length', Buffer.byteLength(jsonString));
|
|
163
|
-
this.originalResponse.end(jsonString);
|
|
164
|
-
},
|
|
165
|
-
send(data) {
|
|
166
|
-
const dataString = typeof data === 'string' ? data : JSON.stringify(data);
|
|
167
|
-
this.originalResponse.statusCode = statusCode;
|
|
168
|
-
this.originalResponse.setHeader('Content-Type', 'text/plain');
|
|
169
|
-
this.originalResponse.setHeader('Content-Length', Buffer.byteLength(dataString));
|
|
170
|
-
this.originalResponse.end(dataString);
|
|
171
|
-
},
|
|
172
|
-
end(data) {
|
|
173
|
-
this.originalResponse.statusCode = statusCode;
|
|
174
|
-
this.originalResponse.end(data);
|
|
175
|
-
}
|
|
176
|
-
};
|
|
177
|
-
}
|
|
178
|
-
// 执行中间件
|
|
179
|
-
async executeMiddleware(middleware, req, res) {
|
|
180
|
-
for (const fn of middleware) {
|
|
181
|
-
let nextCalled = false;
|
|
182
|
-
const next = () => { nextCalled = true; };
|
|
183
|
-
const result = fn(req, res, next);
|
|
184
|
-
if (result instanceof Promise) {
|
|
185
|
-
await result;
|
|
186
|
-
}
|
|
187
|
-
if (!nextCalled) {
|
|
188
|
-
return false; // 中间件已结束响应
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
return true; // 所有中间件都已执行
|
|
192
|
-
}
|
|
193
|
-
// 处理路由请求
|
|
194
|
-
async handleRoute(route, params, req, res) {
|
|
195
|
-
req.params = params;
|
|
196
|
-
// 执行全局中间件
|
|
197
|
-
const globalMiddlewareContinue = await this.executeMiddleware(this.globalMiddleware, req, res);
|
|
198
|
-
if (!globalMiddlewareContinue)
|
|
199
|
-
return;
|
|
200
|
-
// 执行路由中间件
|
|
201
|
-
const routeMiddlewareContinue = await this.executeMiddleware(route.middleware, req, res);
|
|
202
|
-
if (!routeMiddlewareContinue)
|
|
203
|
-
return;
|
|
204
|
-
// 执行路由处理函数
|
|
205
|
-
const result = route.handler(req, res);
|
|
206
|
-
if (result instanceof Promise) {
|
|
207
|
-
await result;
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
}
|
package/modules/http/utils.js
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
import * as http from 'node:http';
|
|
2
|
-
import * as https from 'node:https';
|
|
3
|
-
/**
|
|
4
|
-
* Stream => Buffer
|
|
5
|
-
*/
|
|
6
|
-
export function stream2buffer(stream, totalLength = 0) {
|
|
7
|
-
return new Promise(function (resolve, reject) {
|
|
8
|
-
let buffers = [];
|
|
9
|
-
stream.on('error', reject);
|
|
10
|
-
if (totalLength) {
|
|
11
|
-
stream.on('data', function (data) { buffers.push(data); });
|
|
12
|
-
}
|
|
13
|
-
else {
|
|
14
|
-
stream.on('data', function (data) {
|
|
15
|
-
buffers.push(data);
|
|
16
|
-
totalLength += data.length;
|
|
17
|
-
});
|
|
18
|
-
}
|
|
19
|
-
stream.on('end', function () { resolve(Buffer.concat(buffers, totalLength)); });
|
|
20
|
-
});
|
|
21
|
-
}
|
|
22
|
-
/**
|
|
23
|
-
* Request => JSONObject
|
|
24
|
-
*/
|
|
25
|
-
export async function parseHTTPBody(request) {
|
|
26
|
-
if (request.method === 'GET')
|
|
27
|
-
return null;
|
|
28
|
-
let contentType = request.headers['content-type'];
|
|
29
|
-
// application/json; charset=utf-8
|
|
30
|
-
if (contentType)
|
|
31
|
-
contentType = contentType.split(';')[0].trim();
|
|
32
|
-
const contentLength = request.headers['content-length'];
|
|
33
|
-
if (!contentLength || contentLength === '0')
|
|
34
|
-
return null;
|
|
35
|
-
const contentSize = +contentLength;
|
|
36
|
-
const buffer = await stream2buffer(request, contentSize);
|
|
37
|
-
if (buffer.length !== contentSize)
|
|
38
|
-
throw new Error('Content-Length Incorrect');
|
|
39
|
-
switch (contentType) {
|
|
40
|
-
case 'application/json':
|
|
41
|
-
return JSON.parse(buffer.toString());
|
|
42
|
-
case 'text/plain':
|
|
43
|
-
return buffer.toString();
|
|
44
|
-
default:
|
|
45
|
-
return buffer;
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
/**
|
|
49
|
-
* http request
|
|
50
|
-
*/
|
|
51
|
-
export function httpRequest(url, options, body) {
|
|
52
|
-
return new Promise(function (resolve, reject) {
|
|
53
|
-
const urlObj = typeof url === 'string' ? new URL(url) : url;
|
|
54
|
-
const protocol = urlObj.protocol;
|
|
55
|
-
const client = protocol === 'https:' ? https : http;
|
|
56
|
-
const request = client.request(url, options, async function (response) {
|
|
57
|
-
try {
|
|
58
|
-
const result = await parseHTTPBody(response);
|
|
59
|
-
resolve(result);
|
|
60
|
-
}
|
|
61
|
-
catch (error) {
|
|
62
|
-
const decoration = new Error(`${response.statusCode} - ${error.message}`);
|
|
63
|
-
reject(decoration);
|
|
64
|
-
}
|
|
65
|
-
});
|
|
66
|
-
request.on('error', reject);
|
|
67
|
-
if (body) {
|
|
68
|
-
request.method = 'POST';
|
|
69
|
-
request.setHeader('Content-Type', 'application/json');
|
|
70
|
-
request.setHeader('Content-Length', Buffer.byteLength(body));
|
|
71
|
-
request.write(body);
|
|
72
|
-
}
|
|
73
|
-
request.end();
|
|
74
|
-
});
|
|
75
|
-
}
|
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
import * as http from 'node:http';
|
|
2
|
-
import * as https from 'node:https';
|
|
3
|
-
import Router, { Middleware } from './router.js';
|
|
4
|
-
import { Module, ModuleConfig } from '../module.js';
|
|
5
|
-
export declare class HTTPConfig implements ModuleConfig {
|
|
6
|
-
enabled: boolean;
|
|
7
|
-
port: number;
|
|
8
|
-
path: string;
|
|
9
|
-
origin: string | string[];
|
|
10
|
-
ssl: {
|
|
11
|
-
enabled: boolean;
|
|
12
|
-
cert: string;
|
|
13
|
-
key: string;
|
|
14
|
-
ca: string;
|
|
15
|
-
};
|
|
16
|
-
}
|
|
17
|
-
export default class HTTPModule extends Module {
|
|
18
|
-
name: string;
|
|
19
|
-
config: HTTPConfig;
|
|
20
|
-
server: http.Server | https.Server | null;
|
|
21
|
-
router: Router;
|
|
22
|
-
getURL(): URL;
|
|
23
|
-
get(path: string, ...args: any[]): this;
|
|
24
|
-
post(path: string, ...args: any[]): this;
|
|
25
|
-
put(path: string, ...args: any[]): this;
|
|
26
|
-
delete(path: string, ...args: any[]): this;
|
|
27
|
-
use(middleware: Middleware): this;
|
|
28
|
-
setConfig(config: HTTPConfig): void;
|
|
29
|
-
getConfig(): HTTPConfig;
|
|
30
|
-
get serviceURL(): URL;
|
|
31
|
-
/**
|
|
32
|
-
* start http service
|
|
33
|
-
*/
|
|
34
|
-
serve(): Promise<void>;
|
|
35
|
-
/**
|
|
36
|
-
* stop http service
|
|
37
|
-
*/
|
|
38
|
-
stop(): Promise<void>;
|
|
39
|
-
/**
|
|
40
|
-
* browser cross origin
|
|
41
|
-
*/
|
|
42
|
-
cors(request: http.IncomingMessage, response: http.ServerResponse): boolean;
|
|
43
|
-
requestHandler(request: http.IncomingMessage, response: http.ServerResponse): Promise<void>;
|
|
44
|
-
/**
|
|
45
|
-
* 从请求里获取调用的接口和参数
|
|
46
|
-
*/
|
|
47
|
-
getCallArgsFromRequest(request: http.IncomingMessage): Promise<any>;
|
|
48
|
-
/**
|
|
49
|
-
* HTTP-RPC服务器请求监听方法
|
|
50
|
-
*/
|
|
51
|
-
call(request: http.IncomingMessage, response: http.ServerResponse): Promise<void>;
|
|
52
|
-
/**
|
|
53
|
-
* HTTP Response Catch
|
|
54
|
-
*/
|
|
55
|
-
respond(_request: http.IncomingMessage, response: http.ServerResponse, returns: {
|
|
56
|
-
body?: any;
|
|
57
|
-
success: boolean;
|
|
58
|
-
error?: {
|
|
59
|
-
message: any;
|
|
60
|
-
stack?: any;
|
|
61
|
-
};
|
|
62
|
-
}): void;
|
|
63
|
-
}
|
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import * as http from 'node:http';
|
|
2
|
-
export type RouteHandler = (req: Request, res: Response) => Promise<any> | any;
|
|
3
|
-
export type Middleware = (req: Request, res: Response, next: () => void) => Promise<any> | any;
|
|
4
|
-
export interface Route {
|
|
5
|
-
path: string;
|
|
6
|
-
method: string;
|
|
7
|
-
handler: RouteHandler;
|
|
8
|
-
middleware: Middleware[];
|
|
9
|
-
regex: RegExp;
|
|
10
|
-
paramNames: string[];
|
|
11
|
-
}
|
|
12
|
-
export interface Request {
|
|
13
|
-
originalRequest: http.IncomingMessage;
|
|
14
|
-
url: URL;
|
|
15
|
-
method: string;
|
|
16
|
-
path: string;
|
|
17
|
-
query: Record<string, string>;
|
|
18
|
-
params: Record<string, string>;
|
|
19
|
-
headers: Record<string, string>;
|
|
20
|
-
body: any;
|
|
21
|
-
}
|
|
22
|
-
export interface Response {
|
|
23
|
-
originalResponse: http.ServerResponse;
|
|
24
|
-
status(code: number): Response;
|
|
25
|
-
json(data: any): void;
|
|
26
|
-
send(data: any): void;
|
|
27
|
-
end(data?: any): void;
|
|
28
|
-
}
|
|
29
|
-
export default class Router {
|
|
30
|
-
private routes;
|
|
31
|
-
private globalMiddleware;
|
|
32
|
-
get(path: string, ...args: any[]): void;
|
|
33
|
-
post(path: string, ...args: any[]): void;
|
|
34
|
-
put(path: string, ...args: any[]): void;
|
|
35
|
-
delete(path: string, ...args: any[]): void;
|
|
36
|
-
private parseRouteArgs;
|
|
37
|
-
use(middleware: Middleware): void;
|
|
38
|
-
usePath(path: string, middleware: Middleware): void;
|
|
39
|
-
private addRoute;
|
|
40
|
-
private compilePath;
|
|
41
|
-
match(method: string, path: string): {
|
|
42
|
-
route: Route;
|
|
43
|
-
params: Record<string, string>;
|
|
44
|
-
} | null;
|
|
45
|
-
createRequestObject(originalRequest: http.IncomingMessage, url: URL): Request;
|
|
46
|
-
createResponseObject(originalResponse: http.ServerResponse): Response;
|
|
47
|
-
private executeMiddleware;
|
|
48
|
-
handleRoute(route: Route, params: Record<string, string>, req: Request, res: Response): Promise<void>;
|
|
49
|
-
}
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import * as http from 'node:http';
|
|
2
|
-
import { Readable } from 'node:stream';
|
|
3
|
-
/**
|
|
4
|
-
* Stream => Buffer
|
|
5
|
-
*/
|
|
6
|
-
export declare function stream2buffer(stream: Readable, totalLength?: number): Promise<Buffer>;
|
|
7
|
-
/**
|
|
8
|
-
* Request => JSONObject
|
|
9
|
-
*/
|
|
10
|
-
export declare function parseHTTPBody(request: http.IncomingMessage): Promise<any>;
|
|
11
|
-
/**
|
|
12
|
-
* http request
|
|
13
|
-
*/
|
|
14
|
-
export declare function httpRequest(url: URL | string, options: http.RequestOptions, body: string): Promise<any>;
|