qyani-web 1.0.2 → 1.0.3
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/demo/index.js +18 -0
- package/dist/index.js +240 -16
- package/dist/lib/{GroupRoute.js → group-route.js} +1 -1
- package/package.json +2 -2
- package/src/index.ts +252 -20
- package/src/lib/{GroupRoute.ts → group-route.ts} +1 -1
- package/dist/controllers/index.js +0 -74
- package/dist/lib/app.js +0 -222
- package/dist/routes/index.js +0 -43
- package/dist/utils/certs.js +0 -11
- package/dist/utils/tsl.js +0 -45
- package/index.js +0 -4
- package/src/controllers/index.ts +0 -93
- package/src/lib/app.ts +0 -231
- package/src/public/html/index.html +0 -11
- package/src/public/test.mp4 +0 -0
- package/src/routes/index.ts +0 -51
- package/src/utils/certs.ts +0 -11
- package/src/utils/tsl.ts +0 -44
package/demo/index.js
ADDED
@@ -0,0 +1,18 @@
|
|
1
|
+
// index.js
|
2
|
+
import WebApp from '../dist/index.js'
|
3
|
+
import {requestLogger} from "../dist/lib/middleware/logger.js";
|
4
|
+
const app=new WebApp();
|
5
|
+
app.beforeRequest(requestLogger)
|
6
|
+
const port = 80;
|
7
|
+
// 捕获未处理的异常
|
8
|
+
process.on('uncaughtException', (err) => {
|
9
|
+
console.error('[FATAL] Uncaught Exception:', err);
|
10
|
+
setTimeout(() => process.exit(1), 1000); // 安全退出
|
11
|
+
});
|
12
|
+
process.on('unhandledRejection', (reason, promise) => {
|
13
|
+
console.error('[WARNING] Unhandled Rejection at:', reason, 'Promise', promise);
|
14
|
+
setTimeout(() => process.exit(1), 1000);
|
15
|
+
});
|
16
|
+
app.listen(port, () => {
|
17
|
+
console.log(`Server running on http://localhost:${port}`);
|
18
|
+
});
|
package/dist/index.js
CHANGED
@@ -1,16 +1,240 @@
|
|
1
|
-
//
|
2
|
-
import
|
3
|
-
import
|
4
|
-
|
5
|
-
|
6
|
-
|
7
|
-
|
8
|
-
|
9
|
-
|
10
|
-
|
11
|
-
|
12
|
-
|
13
|
-
|
14
|
-
|
15
|
-
|
16
|
-
|
1
|
+
// app.js
|
2
|
+
import https from 'https';
|
3
|
+
import url from 'url';
|
4
|
+
import * as http from "http";
|
5
|
+
export default class WebApp {
|
6
|
+
constructor() {
|
7
|
+
this.routes = [];
|
8
|
+
this.beforeRequestMiddleWares = [];
|
9
|
+
this.afterRequestMiddleWares = [];
|
10
|
+
}
|
11
|
+
/**
|
12
|
+
* 添加一个前置中间件
|
13
|
+
* @param middleware 中间件函数
|
14
|
+
* @returns 返回当前 WebApp 实例,支持链式调用
|
15
|
+
*/
|
16
|
+
beforeRequest(middleware) {
|
17
|
+
if (typeof middleware !== 'function') {
|
18
|
+
throw new Error('Middleware must be a function');
|
19
|
+
}
|
20
|
+
if (this.beforeRequestMiddleWares.includes(middleware)) {
|
21
|
+
throw new Error('Middleware already exists');
|
22
|
+
}
|
23
|
+
this.beforeRequestMiddleWares.push(middleware);
|
24
|
+
return this;
|
25
|
+
}
|
26
|
+
/**
|
27
|
+
* 添加一个后置中间件
|
28
|
+
* @param middleware 中间件函数
|
29
|
+
* @returns 返回当前 WebApp 实例,支持链式调用
|
30
|
+
*/
|
31
|
+
afterRequest(middleware) {
|
32
|
+
if (typeof middleware !== 'function') {
|
33
|
+
throw new Error('Middleware must be a function');
|
34
|
+
}
|
35
|
+
if (this.afterRequestMiddleWares.includes(middleware)) {
|
36
|
+
throw new Error('Middleware already exists');
|
37
|
+
}
|
38
|
+
this.afterRequestMiddleWares.push(middleware);
|
39
|
+
return this;
|
40
|
+
}
|
41
|
+
/**
|
42
|
+
* 注册一个路由
|
43
|
+
* @param method HTTP 方法,如 'GET', 'POST' 等
|
44
|
+
* @param url 路由路径
|
45
|
+
* @param handler 请求处理函数
|
46
|
+
* @param beforeRequest 在处理函数前执行的中间件数组
|
47
|
+
* @param afterRequest 在处理函数后执行的中间件数组
|
48
|
+
* @returns 返回当前 WebApp 实例,支持链式调用
|
49
|
+
*/
|
50
|
+
request(method, url, handler, beforeRequest = [], afterRequest = []) {
|
51
|
+
this._register(method, url, handler, beforeRequest, afterRequest);
|
52
|
+
return this;
|
53
|
+
}
|
54
|
+
/**
|
55
|
+
* 注册一个 GET 请求路由
|
56
|
+
* @param url 路由路径
|
57
|
+
* @param handler 请求处理函数
|
58
|
+
* @param beforeRequest 在处理函数前执行的中间件数组
|
59
|
+
* @param afterRequest 在处理函数后执行的中间件数组
|
60
|
+
* @returns 返回当前 WebApp 实例,支持链式调用
|
61
|
+
*/
|
62
|
+
get(url, handler, beforeRequest = [], afterRequest = []) {
|
63
|
+
this._register('GET', url, handler, beforeRequest, afterRequest);
|
64
|
+
return this;
|
65
|
+
}
|
66
|
+
/**
|
67
|
+
* 注册一个 POST 请求路由
|
68
|
+
* @param url 路由路径
|
69
|
+
* @param handler 请求处理函数
|
70
|
+
* @param beforeRequest 在处理函数前执行的中间件数组
|
71
|
+
* @param afterRequest 在处理函数后执行的中间件数组
|
72
|
+
* @returns 返回当前 WebApp 实例,支持链式调用
|
73
|
+
*/
|
74
|
+
post(url, handler, beforeRequest = [], afterRequest = []) {
|
75
|
+
this._register('POST', url, handler, beforeRequest, afterRequest);
|
76
|
+
return this;
|
77
|
+
}
|
78
|
+
/**
|
79
|
+
* 注册一个 PUT 请求路由
|
80
|
+
* @param url 路由路径
|
81
|
+
* @param handler 请求处理函数
|
82
|
+
* @param beforeRequest 在处理函数前执行的中间件数组
|
83
|
+
* @param afterRequest 在处理函数后执行的中间件数组
|
84
|
+
* @returns 返回当前 WebApp 实例,支持链式调用
|
85
|
+
*/
|
86
|
+
put(url, handler, beforeRequest = [], afterRequest = []) {
|
87
|
+
this._register('PUT', url, handler, beforeRequest, afterRequest);
|
88
|
+
return this;
|
89
|
+
}
|
90
|
+
/**
|
91
|
+
* 注册一个 DELETE 请求路由
|
92
|
+
* @param url 路由路径
|
93
|
+
* @param handler 请求处理函数
|
94
|
+
* @param beforeRequest 在处理函数前执行的中间件数组
|
95
|
+
* @param afterRequest 在处理函数后执行的中间件数组
|
96
|
+
* @returns 返回当前 WebApp 实例,支持链式调用
|
97
|
+
*/
|
98
|
+
delete(url, handler, beforeRequest = [], afterRequest = []) {
|
99
|
+
this._register('DELETE', url, handler, beforeRequest, afterRequest);
|
100
|
+
return this;
|
101
|
+
}
|
102
|
+
/**
|
103
|
+
* 注册一个路由组
|
104
|
+
* @param groupRoute 路由组实例
|
105
|
+
* @returns 返回当前 WebApp 实例,支持链式调用
|
106
|
+
*/
|
107
|
+
registerGroupRoute(groupRoute) {
|
108
|
+
this.routes.push(...groupRoute.getRoutes());
|
109
|
+
return this;
|
110
|
+
}
|
111
|
+
/**
|
112
|
+
* 匹配路由参数
|
113
|
+
* @param routePath 路由路径
|
114
|
+
* @param requestPath 请求路径
|
115
|
+
* @returns 匹配的参数对象
|
116
|
+
*/
|
117
|
+
matchRoute(routePath, requestPath) {
|
118
|
+
const routeParts = routePath.split('/');
|
119
|
+
const requestParts = requestPath.split('/');
|
120
|
+
if (routeParts.length !== requestParts.length)
|
121
|
+
return null;
|
122
|
+
const params = {};
|
123
|
+
for (let i = 0; i < routeParts.length; i++) {
|
124
|
+
if (routeParts[i] !== requestParts[i] && !routeParts[i].startsWith(':')) {
|
125
|
+
return null;
|
126
|
+
}
|
127
|
+
if (routeParts[i].startsWith(':')) {
|
128
|
+
const paramName = routeParts[i].slice(1);
|
129
|
+
params[paramName] = requestParts[i];
|
130
|
+
}
|
131
|
+
}
|
132
|
+
return params;
|
133
|
+
}
|
134
|
+
/**
|
135
|
+
* 处理请求
|
136
|
+
* @param req 请求对象
|
137
|
+
* @param res 请求响应对象
|
138
|
+
* @private
|
139
|
+
*/
|
140
|
+
async _handleRequest(req, res) {
|
141
|
+
const parsedUrl = new url.URL(req.url ?? '', `http://${req.headers.host}`);
|
142
|
+
const path = parsedUrl.pathname;
|
143
|
+
const method = req.method;
|
144
|
+
// 标记是否结束处理
|
145
|
+
let handled = false;
|
146
|
+
try {
|
147
|
+
//执行前置中间件
|
148
|
+
for (const mw of this.beforeRequestMiddleWares) {
|
149
|
+
if (handled !== true)
|
150
|
+
handled = await mw(req, res);
|
151
|
+
}
|
152
|
+
if (handled)
|
153
|
+
return;
|
154
|
+
// 查找匹配的路由
|
155
|
+
let matchedRoute = null;
|
156
|
+
let params = null;
|
157
|
+
for (let route of this.routes) {
|
158
|
+
if (route.method === method) {
|
159
|
+
params = this.matchRoute(route.url, path);
|
160
|
+
if (params) {
|
161
|
+
matchedRoute = route;
|
162
|
+
break;
|
163
|
+
}
|
164
|
+
}
|
165
|
+
}
|
166
|
+
if (params && matchedRoute) {
|
167
|
+
// 设置请求参数
|
168
|
+
req.query = parsedUrl.searchParams;
|
169
|
+
req.params = params;
|
170
|
+
for (const mw of matchedRoute.chain) {
|
171
|
+
if (!handled)
|
172
|
+
handled = await mw(req, res);
|
173
|
+
}
|
174
|
+
}
|
175
|
+
else {
|
176
|
+
// 404
|
177
|
+
res.writeHead(404, { 'Content-Type': 'application/json' });
|
178
|
+
res.end(JSON.stringify({ error: 'Not Found' }));
|
179
|
+
}
|
180
|
+
}
|
181
|
+
catch (error) {
|
182
|
+
// 500
|
183
|
+
res.writeHead(500, { 'Content-Type': 'application/json' });
|
184
|
+
if (error instanceof Error) {
|
185
|
+
res.end(JSON.stringify({
|
186
|
+
error: 'Internal Server Error',
|
187
|
+
message: error.message,
|
188
|
+
}));
|
189
|
+
console.log(error.stack);
|
190
|
+
}
|
191
|
+
else {
|
192
|
+
res.end(JSON.stringify({
|
193
|
+
error: 'Internal Server Error',
|
194
|
+
message: 'An unknown error occurred.',
|
195
|
+
}));
|
196
|
+
}
|
197
|
+
}
|
198
|
+
finally {
|
199
|
+
//执行后置中间件
|
200
|
+
for (const mw of this.afterRequestMiddleWares) {
|
201
|
+
if (!handled)
|
202
|
+
handled = await mw(req, res);
|
203
|
+
}
|
204
|
+
}
|
205
|
+
}
|
206
|
+
/**
|
207
|
+
* 启动服务器
|
208
|
+
* @param port 端口号
|
209
|
+
* @param callback 回调函数
|
210
|
+
* @param protocol 协议类型
|
211
|
+
* @param certs https证书
|
212
|
+
*/
|
213
|
+
listen(port, callback, protocol = 'http', certs) {
|
214
|
+
let server;
|
215
|
+
if (protocol !== 'https') {
|
216
|
+
server = http.createServer(this._handleRequest.bind(this));
|
217
|
+
}
|
218
|
+
else if (protocol === 'https' && certs) {
|
219
|
+
server = https.createServer(certs, this._handleRequest.bind(this));
|
220
|
+
}
|
221
|
+
else {
|
222
|
+
console.log('未找到证书文件,使用http协议启动');
|
223
|
+
server = http.createServer(this._handleRequest.bind(this));
|
224
|
+
}
|
225
|
+
server.listen(port, callback);
|
226
|
+
}
|
227
|
+
/**
|
228
|
+
* 内部方法,用于注册路由
|
229
|
+
* @param method HTTP 方法
|
230
|
+
* @param url 路由路径
|
231
|
+
* @param handler 请求处理函数
|
232
|
+
* @param beforeRequest 在处理函数前执行的中间件数组
|
233
|
+
* @param afterRequest 在处理函数后执行的中间件数组
|
234
|
+
*/
|
235
|
+
_register(method, url, handler, beforeRequest, afterRequest) {
|
236
|
+
// 构建完整的中间件链:beforeRequest + handler + afterRequest
|
237
|
+
const chain = [...beforeRequest, handler, ...afterRequest];
|
238
|
+
this.routes.push({ method, url, chain });
|
239
|
+
}
|
240
|
+
}
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
@@ -1,20 +1,252 @@
|
|
1
|
-
//
|
2
|
-
import
|
3
|
-
|
4
|
-
import
|
5
|
-
|
6
|
-
|
7
|
-
|
8
|
-
|
9
|
-
|
10
|
-
|
11
|
-
|
12
|
-
|
13
|
-
|
14
|
-
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
|
1
|
+
// app.js
|
2
|
+
import https from 'https';
|
3
|
+
import url from 'url';
|
4
|
+
import GroupRoute from "./lib/group-route";
|
5
|
+
import * as http from "http";
|
6
|
+
import {Handler, Middleware} from "./config/type";
|
7
|
+
|
8
|
+
|
9
|
+
export default class WebApp {
|
10
|
+
private routes: { method: string; url: string; chain: Middleware[] }[] = [];
|
11
|
+
private beforeRequestMiddleWares: Middleware[] = [];
|
12
|
+
private afterRequestMiddleWares: Middleware[] = [];
|
13
|
+
|
14
|
+
constructor() {}
|
15
|
+
|
16
|
+
/**
|
17
|
+
* 添加一个前置中间件
|
18
|
+
* @param middleware 中间件函数
|
19
|
+
* @returns 返回当前 WebApp 实例,支持链式调用
|
20
|
+
*/
|
21
|
+
beforeRequest(middleware: Middleware): this {
|
22
|
+
if (typeof middleware !== 'function') {
|
23
|
+
throw new Error('Middleware must be a function');
|
24
|
+
}
|
25
|
+
if (this.beforeRequestMiddleWares.includes(middleware)) {
|
26
|
+
throw new Error('Middleware already exists');
|
27
|
+
}
|
28
|
+
this.beforeRequestMiddleWares.push(middleware);
|
29
|
+
return this;
|
30
|
+
}
|
31
|
+
|
32
|
+
/**
|
33
|
+
* 添加一个后置中间件
|
34
|
+
* @param middleware 中间件函数
|
35
|
+
* @returns 返回当前 WebApp 实例,支持链式调用
|
36
|
+
*/
|
37
|
+
afterRequest(middleware: Middleware): this {
|
38
|
+
if (typeof middleware !== 'function') {
|
39
|
+
throw new Error('Middleware must be a function');
|
40
|
+
}
|
41
|
+
if (this.afterRequestMiddleWares.includes(middleware)) {
|
42
|
+
throw new Error('Middleware already exists');
|
43
|
+
}
|
44
|
+
this.afterRequestMiddleWares.push(middleware);
|
45
|
+
return this;
|
46
|
+
}
|
47
|
+
|
48
|
+
/**
|
49
|
+
* 注册一个路由
|
50
|
+
* @param method HTTP 方法,如 'GET', 'POST' 等
|
51
|
+
* @param url 路由路径
|
52
|
+
* @param handler 请求处理函数
|
53
|
+
* @param beforeRequest 在处理函数前执行的中间件数组
|
54
|
+
* @param afterRequest 在处理函数后执行的中间件数组
|
55
|
+
* @returns 返回当前 WebApp 实例,支持链式调用
|
56
|
+
*/
|
57
|
+
request(method: string, url: string, handler: Handler, beforeRequest: Middleware[] = [], afterRequest: Middleware[] = []): this {
|
58
|
+
this._register(method, url, handler, beforeRequest, afterRequest);
|
59
|
+
return this;
|
60
|
+
}
|
61
|
+
|
62
|
+
/**
|
63
|
+
* 注册一个 GET 请求路由
|
64
|
+
* @param url 路由路径
|
65
|
+
* @param handler 请求处理函数
|
66
|
+
* @param beforeRequest 在处理函数前执行的中间件数组
|
67
|
+
* @param afterRequest 在处理函数后执行的中间件数组
|
68
|
+
* @returns 返回当前 WebApp 实例,支持链式调用
|
69
|
+
*/
|
70
|
+
get(url: string, handler: Handler, beforeRequest: Middleware[] = [], afterRequest: Middleware[] = []): this {
|
71
|
+
this._register('GET', url, handler, beforeRequest, afterRequest);
|
72
|
+
return this;
|
73
|
+
}
|
74
|
+
|
75
|
+
/**
|
76
|
+
* 注册一个 POST 请求路由
|
77
|
+
* @param url 路由路径
|
78
|
+
* @param handler 请求处理函数
|
79
|
+
* @param beforeRequest 在处理函数前执行的中间件数组
|
80
|
+
* @param afterRequest 在处理函数后执行的中间件数组
|
81
|
+
* @returns 返回当前 WebApp 实例,支持链式调用
|
82
|
+
*/
|
83
|
+
post(url: string, handler: Handler, beforeRequest: Middleware[] = [], afterRequest: Middleware[] = []): this {
|
84
|
+
this._register('POST', url, handler, beforeRequest, afterRequest);
|
85
|
+
return this;
|
86
|
+
}
|
87
|
+
|
88
|
+
/**
|
89
|
+
* 注册一个 PUT 请求路由
|
90
|
+
* @param url 路由路径
|
91
|
+
* @param handler 请求处理函数
|
92
|
+
* @param beforeRequest 在处理函数前执行的中间件数组
|
93
|
+
* @param afterRequest 在处理函数后执行的中间件数组
|
94
|
+
* @returns 返回当前 WebApp 实例,支持链式调用
|
95
|
+
*/
|
96
|
+
put(url: string, handler: Handler, beforeRequest: Middleware[] = [], afterRequest: Middleware[] = []): this {
|
97
|
+
this._register('PUT', url, handler, beforeRequest, afterRequest);
|
98
|
+
return this;
|
99
|
+
}
|
100
|
+
|
101
|
+
/**
|
102
|
+
* 注册一个 DELETE 请求路由
|
103
|
+
* @param url 路由路径
|
104
|
+
* @param handler 请求处理函数
|
105
|
+
* @param beforeRequest 在处理函数前执行的中间件数组
|
106
|
+
* @param afterRequest 在处理函数后执行的中间件数组
|
107
|
+
* @returns 返回当前 WebApp 实例,支持链式调用
|
108
|
+
*/
|
109
|
+
delete(url: string, handler: Handler, beforeRequest: Middleware[] = [], afterRequest: Middleware[] = []): this {
|
110
|
+
this._register('DELETE', url, handler, beforeRequest, afterRequest);
|
111
|
+
return this;
|
112
|
+
}
|
113
|
+
|
114
|
+
/**
|
115
|
+
* 注册一个路由组
|
116
|
+
* @param groupRoute 路由组实例
|
117
|
+
* @returns 返回当前 WebApp 实例,支持链式调用
|
118
|
+
*/
|
119
|
+
registerGroupRoute(groupRoute: GroupRoute): this {
|
120
|
+
this.routes.push(...groupRoute.getRoutes());
|
121
|
+
return this;
|
122
|
+
}
|
123
|
+
|
124
|
+
/**
|
125
|
+
* 匹配路由参数
|
126
|
+
* @param routePath 路由路径
|
127
|
+
* @param requestPath 请求路径
|
128
|
+
* @returns 匹配的参数对象
|
129
|
+
*/
|
130
|
+
matchRoute(routePath: string, requestPath: string): Record<string, string> | null {
|
131
|
+
const routeParts = routePath.split('/');
|
132
|
+
const requestParts = requestPath.split('/');
|
133
|
+
|
134
|
+
if (routeParts.length !== requestParts.length) return null;
|
135
|
+
|
136
|
+
const params: Record<string, string> = {};
|
137
|
+
for (let i = 0; i < routeParts.length; i++) {
|
138
|
+
if (routeParts[i] !== requestParts[i] && !routeParts[i].startsWith(':')) {
|
139
|
+
return null;
|
140
|
+
}
|
141
|
+
if (routeParts[i].startsWith(':')) {
|
142
|
+
const paramName = routeParts[i].slice(1);
|
143
|
+
params[paramName] = requestParts[i];
|
144
|
+
}
|
145
|
+
}
|
146
|
+
|
147
|
+
return params;
|
148
|
+
}
|
149
|
+
|
150
|
+
/**
|
151
|
+
* 处理请求
|
152
|
+
* @param req 请求对象
|
153
|
+
* @param res 请求响应对象
|
154
|
+
* @private
|
155
|
+
*/
|
156
|
+
private async _handleRequest(req: http.IncomingMessage, res: http.ServerResponse) {
|
157
|
+
const parsedUrl = new url.URL(req.url ?? '', `http://${req.headers.host}`);
|
158
|
+
const path = parsedUrl.pathname;
|
159
|
+
const method = req.method;
|
160
|
+
|
161
|
+
// 标记是否结束处理
|
162
|
+
let handled: boolean | Promise<boolean> | undefined = false;
|
163
|
+
try {
|
164
|
+
//执行前置中间件
|
165
|
+
for (const mw of this.beforeRequestMiddleWares) {
|
166
|
+
if (handled !== true) handled = await mw(req, res);
|
167
|
+
}
|
168
|
+
if (handled) return;
|
169
|
+
// 查找匹配的路由
|
170
|
+
let matchedRoute: { method: string; url: string; chain: Middleware[] } | null = null
|
171
|
+
let params: Record<string, string> | null = null;
|
172
|
+
|
173
|
+
for (let route of this.routes) {
|
174
|
+
if (route.method === method) {
|
175
|
+
params = this.matchRoute(route.url, path);
|
176
|
+
if (params) {
|
177
|
+
matchedRoute = route;
|
178
|
+
break;
|
179
|
+
}
|
180
|
+
}
|
181
|
+
}
|
182
|
+
if (params && matchedRoute) {
|
183
|
+
// 设置请求参数
|
184
|
+
(req as any).query = parsedUrl.searchParams;
|
185
|
+
(req as any).params = params;
|
186
|
+
for (const mw of matchedRoute.chain) {
|
187
|
+
if (!handled) handled = await mw(req, res);
|
188
|
+
}
|
189
|
+
} else {
|
190
|
+
// 404
|
191
|
+
res.writeHead(404, {'Content-Type': 'application/json'});
|
192
|
+
res.end(JSON.stringify({error: 'Not Found'}));
|
193
|
+
}
|
194
|
+
} catch (error: unknown) {
|
195
|
+
// 500
|
196
|
+
res.writeHead(500, {'Content-Type': 'application/json'});
|
197
|
+
if (error instanceof Error) {
|
198
|
+
res.end(JSON.stringify({
|
199
|
+
error: 'Internal Server Error',
|
200
|
+
message: error.message,
|
201
|
+
}));
|
202
|
+
console.log(error.stack);
|
203
|
+
} else {
|
204
|
+
res.end(JSON.stringify({
|
205
|
+
error: 'Internal Server Error',
|
206
|
+
message: 'An unknown error occurred.',
|
207
|
+
}));
|
208
|
+
}
|
209
|
+
} finally {
|
210
|
+
//执行后置中间件
|
211
|
+
for (const mw of this.afterRequestMiddleWares) {
|
212
|
+
if (!handled) handled = await mw(req, res);
|
213
|
+
}
|
214
|
+
}
|
215
|
+
}
|
216
|
+
|
217
|
+
/**
|
218
|
+
* 启动服务器
|
219
|
+
* @param port 端口号
|
220
|
+
* @param callback 回调函数
|
221
|
+
* @param protocol 协议类型
|
222
|
+
* @param certs https证书
|
223
|
+
*/
|
224
|
+
listen(port: number, callback: () => void,protocol:string = 'http',certs?:{cert:string,key:string}): void {
|
225
|
+
let server;
|
226
|
+
if (protocol !== 'https') {
|
227
|
+
server = http.createServer(this._handleRequest.bind(this));
|
228
|
+
}
|
229
|
+
else if (protocol === 'https' && certs) {
|
230
|
+
server = https.createServer(certs, this._handleRequest.bind(this));
|
231
|
+
}
|
232
|
+
else {
|
233
|
+
console.log('未找到证书文件,使用http协议启动');
|
234
|
+
server = http.createServer(this._handleRequest.bind(this));
|
235
|
+
}
|
236
|
+
server.listen(port, callback);
|
237
|
+
}
|
238
|
+
|
239
|
+
/**
|
240
|
+
* 内部方法,用于注册路由
|
241
|
+
* @param method HTTP 方法
|
242
|
+
* @param url 路由路径
|
243
|
+
* @param handler 请求处理函数
|
244
|
+
* @param beforeRequest 在处理函数前执行的中间件数组
|
245
|
+
* @param afterRequest 在处理函数后执行的中间件数组
|
246
|
+
*/
|
247
|
+
private _register(method: string, url: string, handler: Handler, beforeRequest: Middleware[], afterRequest: Middleware[]): void {
|
248
|
+
// 构建完整的中间件链:beforeRequest + handler + afterRequest
|
249
|
+
const chain = [...beforeRequest, handler, ...afterRequest];
|
250
|
+
this.routes.push({method, url, chain});
|
251
|
+
}
|
252
|
+
}
|
@@ -21,7 +21,7 @@ type Handler = (req: http.IncomingMessage, res: http.ServerResponse) => boolean
|
|
21
21
|
* GroupRoute 类用于组织和管理一组具有共同前缀的 HTTP 路由。
|
22
22
|
* 支持在请求处理前后添加中间件,并支持链式调用。
|
23
23
|
*/
|
24
|
-
export class GroupRoute {
|
24
|
+
export default class GroupRoute {
|
25
25
|
// 在请求处理前执行的中间件列表
|
26
26
|
private beforeRequestMiddleWares: Middleware[] = [];
|
27
27
|
|
@@ -1,74 +0,0 @@
|
|
1
|
-
"use strict";
|
2
|
-
/**
|
3
|
-
* 首页
|
4
|
-
* @param req
|
5
|
-
* @param res
|
6
|
-
*/
|
7
|
-
export const index = (req, res) => {
|
8
|
-
const request = req;
|
9
|
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
10
|
-
res.end(JSON.stringify({
|
11
|
-
message: 'Welcome to Qianrenni\'s WebApp FrameWork',
|
12
|
-
query: Object.fromEntries(request.query ?? {}),
|
13
|
-
params: request.params ?? {}
|
14
|
-
}));
|
15
|
-
return true;
|
16
|
-
};
|
17
|
-
/**
|
18
|
-
* 用户详情
|
19
|
-
* @param req
|
20
|
-
* @param res
|
21
|
-
*/
|
22
|
-
export const userDetail = (req, res) => {
|
23
|
-
const request = req;
|
24
|
-
// 确保 query 存在并转换为 Record 类型
|
25
|
-
const queryParams = request.query
|
26
|
-
? Object.entries(request.query)
|
27
|
-
: {};
|
28
|
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
29
|
-
res.end(JSON.stringify({
|
30
|
-
id: request.params?.id,
|
31
|
-
query: queryParams
|
32
|
-
}));
|
33
|
-
return true;
|
34
|
-
};
|
35
|
-
import fs from 'fs/promises';
|
36
|
-
import path from 'path';
|
37
|
-
import { fileURLToPath } from 'url';
|
38
|
-
// 替换 __dirname
|
39
|
-
const __filename = fileURLToPath(import.meta.url);
|
40
|
-
const __dirname = path.dirname(__filename);
|
41
|
-
// 确保 public 目录存在
|
42
|
-
const PUBLIC_DIR = path.join(__dirname, '../public');
|
43
|
-
fs.access(PUBLIC_DIR)
|
44
|
-
.then(() => { })
|
45
|
-
.catch(async () => {
|
46
|
-
await fs.mkdir(PUBLIC_DIR, { recursive: true }); // 添加 recursive 避免多级目录问题
|
47
|
-
});
|
48
|
-
/**
|
49
|
-
* 上传文件
|
50
|
-
* @param req
|
51
|
-
* @param res
|
52
|
-
*/
|
53
|
-
export const uploadFiles = async (req, res) => {
|
54
|
-
const request = req;
|
55
|
-
const data = request.body;
|
56
|
-
const savedFiles = [];
|
57
|
-
const keys = Object.keys(data?.fields);
|
58
|
-
if (data?.files) {
|
59
|
-
for (const file of data.files) {
|
60
|
-
const filePath = path.join(PUBLIC_DIR, file.filename);
|
61
|
-
await fs.writeFile(filePath, file.data);
|
62
|
-
savedFiles.push(file.filename);
|
63
|
-
console.log(`文件已保存至: ${filePath}`);
|
64
|
-
}
|
65
|
-
}
|
66
|
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
67
|
-
res.end(JSON.stringify({
|
68
|
-
status: 'success',
|
69
|
-
message: `${savedFiles.length} 个文件 ${keys.length} 参数上传成功`,
|
70
|
-
files: data?.files?.map(f => f.filename),
|
71
|
-
fields: keys
|
72
|
-
}));
|
73
|
-
return true;
|
74
|
-
};
|