qyani-web 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -0
- package/index.js +4 -0
- package/keys/cert.pem +19 -0
- package/keys/key.pem +27 -0
- package/package.json +25 -0
- package/src/config/type.ts +44 -0
- package/src/controllers/index.ts +93 -0
- package/src/index.ts +20 -0
- package/src/lib/GroupRoute.ts +153 -0
- package/src/lib/app.ts +232 -0
- package/src/lib/middleware/body-parser.ts +175 -0
- package/src/lib/middleware/cors.ts +64 -0
- package/src/lib/middleware/logger.ts +95 -0
- package/src/lib/middleware/static-resources.ts +94 -0
- package/src/lib/middleware/validate.ts +169 -0
- package/src/public/html/index.html +11 -0
- package/src/public/test.mp4 +0 -0
- package/src/routes/index.ts +51 -0
- package/src/utils/certs.ts +11 -0
- package/src/utils/tsl.ts +44 -0
- package/tsconfig.json +15 -0
@@ -0,0 +1,175 @@
|
|
1
|
+
// 解析 application/json
|
2
|
+
/*
|
3
|
+
* 解析 application/json
|
4
|
+
* @param {string} rawBody - 待解析的 JSON 字符串
|
5
|
+
* @returns {object} 解析后的 JSON 对象
|
6
|
+
*/
|
7
|
+
import http from "http";
|
8
|
+
import Bb from 'busboy'
|
9
|
+
import {FileInfo, ProcessRequest} from "../../config/type";
|
10
|
+
|
11
|
+
function parseJson(rawBody: string): {fields: Record<string, string>, files: FileInfo[]} {
|
12
|
+
try {
|
13
|
+
let result=JSON.parse(rawBody);
|
14
|
+
console.log("parseJson",result);
|
15
|
+
return {fields:result, files:[]};
|
16
|
+
} catch (e) {
|
17
|
+
throw new Error('Invalid JSON');
|
18
|
+
}
|
19
|
+
}
|
20
|
+
|
21
|
+
// 解析 application/x-www-form-urlencoded
|
22
|
+
/*
|
23
|
+
* 解析 application/x-www-form-urlencoded
|
24
|
+
* @param {string} rawBody - 待解析的表单数据
|
25
|
+
* @returns Record<string, string> 解析后的表单数据
|
26
|
+
*/
|
27
|
+
function parseForm(rawBody: string): { fields: Record<string, string>, files: FileInfo[] } {
|
28
|
+
const params = new URLSearchParams(rawBody);
|
29
|
+
const form: Record<string, string> = {};
|
30
|
+
for (const [key, value] of params.entries()) {
|
31
|
+
form[key] = value;
|
32
|
+
}
|
33
|
+
console.log("parseForm",form);
|
34
|
+
return { fields: form, files: []};
|
35
|
+
}
|
36
|
+
|
37
|
+
/*
|
38
|
+
* 解析 multipart/form-data
|
39
|
+
* @param {http.IncomingMessage} req - 请求对象
|
40
|
+
* @returns {Promise<{fields: Record<string, string>, files: any[]}>} 解析结果
|
41
|
+
*/
|
42
|
+
function parseMultipart(req:http.IncomingMessage) {
|
43
|
+
return new Promise<{fields: Record<string, string>, files: FileInfo[]}>((resolve, reject) => {
|
44
|
+
// const bb = import('busboy')({
|
45
|
+
// headers: req.headers,
|
46
|
+
// limits: {
|
47
|
+
// fileSize: 10*1024*1024 ,// 最大 10MB
|
48
|
+
// files:10
|
49
|
+
// }
|
50
|
+
// }
|
51
|
+
// );
|
52
|
+
|
53
|
+
const bb=Bb({
|
54
|
+
headers: req.headers,
|
55
|
+
limits: {
|
56
|
+
fileSize: 10*1024*1024 ,// 最大 10MB
|
57
|
+
files:10
|
58
|
+
}
|
59
|
+
})
|
60
|
+
const fields: Record<string, string> = {};
|
61
|
+
const files: FileInfo[] = [];
|
62
|
+
|
63
|
+
// 普通字段
|
64
|
+
bb.on('field', (name:string, value:string) => {
|
65
|
+
fields[name] = value;
|
66
|
+
});
|
67
|
+
|
68
|
+
// 文件字段
|
69
|
+
bb.on('file', (fieldname:string, file, info:{filename:string, mimeType:string, encoding:string}) => {
|
70
|
+
const { filename, mimeType, encoding } = info;
|
71
|
+
const chunks: Buffer[] = [];
|
72
|
+
|
73
|
+
console.log(`File [${fieldname}]: ${filename}, ${mimeType}`);
|
74
|
+
// ✅ 关键:监听 'limit' 事件
|
75
|
+
file.on('limit', () => {
|
76
|
+
req.unpipe(bb);
|
77
|
+
reject(new Error( `${filename}文件大小超出限制`));
|
78
|
+
});
|
79
|
+
file.on('data', (chunk) => {
|
80
|
+
chunks.push(chunk);
|
81
|
+
});
|
82
|
+
|
83
|
+
file.on('end', () => {
|
84
|
+
files.push({
|
85
|
+
fieldname,
|
86
|
+
filename,
|
87
|
+
mimetype: mimeType,
|
88
|
+
encoding,
|
89
|
+
data: Buffer.concat(chunks)
|
90
|
+
});
|
91
|
+
console.log(`文件 [${fieldname}] 接收完成`);
|
92
|
+
});
|
93
|
+
|
94
|
+
file.on('error', (err) => {
|
95
|
+
reject(err);
|
96
|
+
});
|
97
|
+
});
|
98
|
+
|
99
|
+
// 完成解析
|
100
|
+
bb.on('finish', () => {
|
101
|
+
resolve({ fields, files });
|
102
|
+
});
|
103
|
+
|
104
|
+
// 错误处理
|
105
|
+
bb.on('error', (err) => {
|
106
|
+
reject(err);
|
107
|
+
});
|
108
|
+
// 文件数量超出限制
|
109
|
+
bb.on('filesLimit', () => {
|
110
|
+
req.unpipe(bb);
|
111
|
+
reject(new Error('文件数量超过限制'));
|
112
|
+
});
|
113
|
+
|
114
|
+
// 字段数量超出限制
|
115
|
+
bb.on('fieldsLimit', () => {
|
116
|
+
req.unpipe(bb);
|
117
|
+
reject(new Error('字段数量超过限制'));
|
118
|
+
});
|
119
|
+
|
120
|
+
// 管道输入
|
121
|
+
req.pipe(bb);
|
122
|
+
});
|
123
|
+
}
|
124
|
+
|
125
|
+
// 映射 Content-Type 到对应的解析函数
|
126
|
+
const parserType=[ 'application/json','application/x-www-form-urlencoded','multipart/form-data']
|
127
|
+
|
128
|
+
/**
|
129
|
+
* 解析请求体
|
130
|
+
* @param req http.IncomingMessage 请求对象
|
131
|
+
* @param res http.ServerResponse 响应对象
|
132
|
+
* @returns {Promise<boolean>} 是否结束处理
|
133
|
+
*/
|
134
|
+
export async function bodyParser(req:http.IncomingMessage, res:http.ServerResponse) {
|
135
|
+
|
136
|
+
const contentType = req.headers['content-type'] || '';
|
137
|
+
|
138
|
+
(req as ProcessRequest).body=await new Promise<{ fields: Record<string, string>, files: FileInfo[] }>((resolve, reject) => {
|
139
|
+
const matchedType = parserType.find(type => type===contentType)
|
140
|
+
|
141
|
+
if (!matchedType) {
|
142
|
+
return resolve({fields:{}, files:[]});
|
143
|
+
}
|
144
|
+
|
145
|
+
if (matchedType === 'multipart/form-data') {
|
146
|
+
parseMultipart(req)
|
147
|
+
.then(data => resolve(data))
|
148
|
+
.catch(err => reject(err));
|
149
|
+
} else {
|
150
|
+
|
151
|
+
// 处理其他类型
|
152
|
+
let body: Buffer[] = [];
|
153
|
+
req.on('data', chunk => {
|
154
|
+
body.push(chunk);
|
155
|
+
});
|
156
|
+
|
157
|
+
req.on('end', () => {
|
158
|
+
const rawBody = Buffer.concat(body).toString();
|
159
|
+
try {
|
160
|
+
const result = contentType==='application/json'?parseJson(rawBody):parseForm(rawBody);
|
161
|
+
resolve(result);
|
162
|
+
} catch (e) {
|
163
|
+
reject(e);
|
164
|
+
}
|
165
|
+
});
|
166
|
+
|
167
|
+
req.on('error', (err) => {
|
168
|
+
reject(err);
|
169
|
+
});
|
170
|
+
}
|
171
|
+
|
172
|
+
});
|
173
|
+
|
174
|
+
return false; // 继续执行下一个中间件
|
175
|
+
}
|
@@ -0,0 +1,64 @@
|
|
1
|
+
// middlewares/cors.js
|
2
|
+
/*
|
3
|
+
* 跨域中间件配置项
|
4
|
+
*/
|
5
|
+
import http from "http";
|
6
|
+
|
7
|
+
type CorsOptions = {
|
8
|
+
origin?: string | string[];//允许的源
|
9
|
+
methods?: string[];//允许的方法
|
10
|
+
allowedHeaders?: string[];//允许的请求头
|
11
|
+
credentials?: boolean;//允许携带cookie
|
12
|
+
};
|
13
|
+
/*
|
14
|
+
* 跨域中间件
|
15
|
+
* @param options 跨域配置项
|
16
|
+
* @returns 中间件函数
|
17
|
+
*/
|
18
|
+
export function cors(options: CorsOptions = {}) {
|
19
|
+
const {
|
20
|
+
origin = '*',
|
21
|
+
methods = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
|
22
|
+
allowedHeaders = ['Content-Type', 'Authorization'],
|
23
|
+
credentials = false,
|
24
|
+
} = options;
|
25
|
+
|
26
|
+
return function corsMiddleware(req: http.IncomingMessage, res: http.ServerResponse) {
|
27
|
+
const requestOrigin = req.headers.origin;
|
28
|
+
|
29
|
+
if (requestOrigin) {
|
30
|
+
let allowThisOrigin = false;
|
31
|
+
|
32
|
+
if (origin === '*') {
|
33
|
+
allowThisOrigin = true;
|
34
|
+
} else if (Array.isArray(origin)) {
|
35
|
+
allowThisOrigin = origin.some(host => host === requestOrigin);
|
36
|
+
}
|
37
|
+
|
38
|
+
if (allowThisOrigin) {
|
39
|
+
// 设置 CORS 响应头
|
40
|
+
res.setHeader('Access-Control-Allow-Origin', requestOrigin);
|
41
|
+
|
42
|
+
if (credentials) {
|
43
|
+
res.setHeader('Access-Control-Allow-Credentials', 'true');
|
44
|
+
}
|
45
|
+
res.setHeader('Access-Control-Allow-Methods', methods.join(', '));
|
46
|
+
res.setHeader('Access-Control-Allow-Headers', allowedHeaders.join(', '));
|
47
|
+
|
48
|
+
// 处理 OPTIONS 预检请求
|
49
|
+
if (req.method === 'OPTIONS') {
|
50
|
+
res.writeHead(204); // No Content
|
51
|
+
res.end();
|
52
|
+
return true; // 已处理
|
53
|
+
}
|
54
|
+
} else {
|
55
|
+
console.warn(`Blocked request from disallowed origin: ${requestOrigin}`);
|
56
|
+
res.writeHead(403, { 'Content-Type': 'text/plain' });
|
57
|
+
res.end('Forbidden');
|
58
|
+
return true;
|
59
|
+
}
|
60
|
+
}
|
61
|
+
|
62
|
+
return false; // 继续后续处理
|
63
|
+
};
|
64
|
+
}
|
@@ -0,0 +1,95 @@
|
|
1
|
+
// middleware/logger.js
|
2
|
+
|
3
|
+
/*
|
4
|
+
* 获取当前时间
|
5
|
+
* @return {string} 格式化后的时间字符串
|
6
|
+
*/
|
7
|
+
import http from "http";
|
8
|
+
import {Middleware} from "../../config/type";
|
9
|
+
|
10
|
+
export function formatLocalTime(){
|
11
|
+
const date=new Date();
|
12
|
+
const year = date.getFullYear();
|
13
|
+
const month = String(date.getMonth() + 1).padStart(2, '0');
|
14
|
+
const day = String(date.getDate()).padStart(2, '0');
|
15
|
+
const hours = String(date.getHours()).padStart(2, '0');
|
16
|
+
const minutes = String(date.getMinutes()).padStart(2, '0');
|
17
|
+
const seconds = String(date.getSeconds()).padStart(2, '0');
|
18
|
+
|
19
|
+
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
|
20
|
+
}
|
21
|
+
|
22
|
+
/*
|
23
|
+
* 请求日志记录
|
24
|
+
* @param {http.IncomingMessage} req 请求对象
|
25
|
+
* @param {http.ServerResponse} res 响应对象
|
26
|
+
* @return {boolean} 默认返回 false,表示继续执行后续逻辑
|
27
|
+
*/
|
28
|
+
export const requestLogger = (req:http.IncomingMessage, res:http.ServerResponse) => {
|
29
|
+
const method = req.method;
|
30
|
+
const url = req.url;
|
31
|
+
const timestamp = formatLocalTime();
|
32
|
+
|
33
|
+
console.log(`[${timestamp}] ${req.headers.origin||''} request ${method} ${url} `);
|
34
|
+
return false; // 继续执行后续逻辑
|
35
|
+
};
|
36
|
+
|
37
|
+
/*
|
38
|
+
* 响应日志记录
|
39
|
+
* @param {http.IncomingMessage} req 请求对象
|
40
|
+
* @param {http.ServerResponse} res 响应对象
|
41
|
+
* @return {boolean} 默认返回 false,表示继续执行后续逻辑
|
42
|
+
*/
|
43
|
+
export const responseLogger = (req:http.IncomingMessage, res:http.ServerResponse) => {
|
44
|
+
const startTime = process.hrtime();
|
45
|
+
// 保存原始 end 方法
|
46
|
+
const originalEnd = res.end;
|
47
|
+
|
48
|
+
// 覆盖 res.end 方法以捕获响应结束
|
49
|
+
res.end = function (this: typeof res, chunk?: any, encoding?: BufferEncoding | (() => void), callback?: () => void): typeof res {
|
50
|
+
const [seconds, nanoseconds] = process.hrtime(startTime);
|
51
|
+
const durationMs = Math.round(seconds * 1000 + nanoseconds / 1e6);
|
52
|
+
|
53
|
+
const statusCode = res.statusCode || 500;
|
54
|
+
const timestamp = formatLocalTime();
|
55
|
+
|
56
|
+
console.log(
|
57
|
+
`[${timestamp}] ${req.headers.origin||''} response ${req.method} ${req.url} ${statusCode} ${durationMs}ms`
|
58
|
+
);
|
59
|
+
|
60
|
+
return originalEnd.call(this, chunk, encoding as BufferEncoding, callback);
|
61
|
+
};
|
62
|
+
return false; // 继续执行后续逻辑
|
63
|
+
};
|
64
|
+
|
65
|
+
// function errorLoggerInjection(app){
|
66
|
+
// if (!app)
|
67
|
+
// throw new Error('app is required');
|
68
|
+
// // 所有路由注册前自动包装 handler
|
69
|
+
// app.routes = app.routes.map(route => ({
|
70
|
+
// ...route,
|
71
|
+
// handler: wrapHandler(route.handler)
|
72
|
+
// }));
|
73
|
+
// }
|
74
|
+
//
|
75
|
+
// function wrapHandler(handler:Middleware) {
|
76
|
+
// return (req, res) => {
|
77
|
+
// Promise.resolve()
|
78
|
+
// .then(() => handler(req, res))
|
79
|
+
// .catch(error => {
|
80
|
+
// const timestamp = formatLocalTime();
|
81
|
+
// const method = req.method;
|
82
|
+
// const url = req.url;
|
83
|
+
// console.error(`[${timestamp}] ERROR ${method} ${url}`);
|
84
|
+
// console.error('Error Stack:',error.stack);
|
85
|
+
// if(!res.headersSent){
|
86
|
+
// res.writeHead(500, { 'Content-Type': 'application/json' });
|
87
|
+
// }
|
88
|
+
// res.end(JSON.stringify({
|
89
|
+
// error: 'Internal Server Error',
|
90
|
+
// message: error.message
|
91
|
+
// }));
|
92
|
+
// });
|
93
|
+
// };
|
94
|
+
// }
|
95
|
+
console.log('logger.js loaded')
|
@@ -0,0 +1,94 @@
|
|
1
|
+
import fs from 'fs'
|
2
|
+
import path from 'path'
|
3
|
+
import http from "http";
|
4
|
+
/*
|
5
|
+
* 解析文件类型
|
6
|
+
* @param extension 文件扩展名
|
7
|
+
* @returns string 文件类型
|
8
|
+
*/
|
9
|
+
function getContentType(extname: string): string {
|
10
|
+
const map: Record<string, string>= {
|
11
|
+
'.html': 'text/html',
|
12
|
+
'.js': 'text/javascript',
|
13
|
+
'.css': 'text/css',
|
14
|
+
'.json': 'application/json',
|
15
|
+
'.png': 'image/png',
|
16
|
+
'.jpg': 'image/jpeg',
|
17
|
+
'.gif': 'image/gif',
|
18
|
+
'.svg': 'image/svg+xml',
|
19
|
+
'.txt': 'text/plain',
|
20
|
+
'.woff': 'font/woff',
|
21
|
+
'.woff2': 'font/woff2',
|
22
|
+
'.ttf': 'font/ttf',
|
23
|
+
'.eot': 'application/vnd.ms-fontobject',
|
24
|
+
'.mp3': 'audio/mpeg',
|
25
|
+
'.mp4': 'video/mp4',
|
26
|
+
'.wav': 'audio/wav',
|
27
|
+
'.pdf': 'application/pdf',
|
28
|
+
'.zip': 'application/zip',
|
29
|
+
'.doc': 'application/msword',
|
30
|
+
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
31
|
+
'.xls': 'application/vnd.ms-excel',
|
32
|
+
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
33
|
+
'.ppt': 'application/vnd.ms-powerpoint',
|
34
|
+
'.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
35
|
+
'.webp': 'image/webp'
|
36
|
+
};
|
37
|
+
return map[extname] || 'application/octet-stream';
|
38
|
+
}
|
39
|
+
|
40
|
+
|
41
|
+
/*
|
42
|
+
* 静态资源配置项
|
43
|
+
* @param prefix URL 前缀
|
44
|
+
* @param rootDir 静态资源根目录
|
45
|
+
*/
|
46
|
+
type StaticResourcesOptions = {
|
47
|
+
prefix?: string;
|
48
|
+
rootDir?: string;
|
49
|
+
};
|
50
|
+
/*
|
51
|
+
* 静态资源中间件
|
52
|
+
* @param options 配置项
|
53
|
+
* @returns 返回一个中间件函数
|
54
|
+
*/
|
55
|
+
export const staticResources = function (options: StaticResourcesOptions = {}){
|
56
|
+
const { prefix = '/public', // URL 前缀
|
57
|
+
rootDir = path.join(process.cwd(), prefix) // 默认 public 目录
|
58
|
+
} = options;
|
59
|
+
console.log('静态资源中间件已启动...', rootDir);
|
60
|
+
return async function (req: http.IncomingMessage, res: http.ServerResponse) {
|
61
|
+
const parsedUrl = new URL(req.url?? '', `http://${req.headers.host}`);
|
62
|
+
const pathname = parsedUrl.pathname;
|
63
|
+
// 检查是否匹配前缀
|
64
|
+
if (!pathname.startsWith(prefix)) {
|
65
|
+
return false; // 继续后续中间件
|
66
|
+
}
|
67
|
+
// 构建实际文件路径
|
68
|
+
const filePath = pathname.replace(prefix, '');
|
69
|
+
const fullPath = path.join(rootDir, filePath);
|
70
|
+
try {
|
71
|
+
const stats = await fs.promises.stat(fullPath);
|
72
|
+
if (!stats.isFile()) {
|
73
|
+
res.writeHead(404, { 'Content-Type': 'text/plain' });
|
74
|
+
res.end('Not Found');
|
75
|
+
return true; // 中断中间件链
|
76
|
+
}
|
77
|
+
const extname = path.extname(fullPath).toLowerCase();
|
78
|
+
const contentType = getContentType(extname);
|
79
|
+
res.writeHead(200, { 'Content-Type': contentType });
|
80
|
+
fs.createReadStream(fullPath).pipe(res);
|
81
|
+
return true; // 已响应,中断后续流程
|
82
|
+
}
|
83
|
+
catch (err:unknown) {
|
84
|
+
res.writeHead(404, { 'Content-Type': 'text/plain' });
|
85
|
+
res.end('Not Found');
|
86
|
+
if(err instanceof Error){
|
87
|
+
console.error('静态资源访问错误:', err.message);
|
88
|
+
}
|
89
|
+
|
90
|
+
|
91
|
+
return true; // 中断流程
|
92
|
+
}
|
93
|
+
};
|
94
|
+
};
|
@@ -0,0 +1,169 @@
|
|
1
|
+
import { formatLocalTime } from './logger.js';
|
2
|
+
import http from "http";
|
3
|
+
import {ProcessRequest} from "../../config/type";
|
4
|
+
|
5
|
+
/**
|
6
|
+
* 字段验证规则类型定义
|
7
|
+
*/
|
8
|
+
type ValidationRule = {
|
9
|
+
required?: boolean; // 是否必填
|
10
|
+
optional?: boolean; // 是否可选(与required互斥)
|
11
|
+
type?: 'string' | 'number' | 'boolean'; // 期望的类型
|
12
|
+
min?: number; // 最小长度(仅字符串)
|
13
|
+
max?: number; // 最大长度(仅字符串)
|
14
|
+
format?: 'email'; // 格式验证(目前只支持email)
|
15
|
+
};
|
16
|
+
|
17
|
+
/**
|
18
|
+
* 验证配置类型定义
|
19
|
+
* 可以对body、query、params分别设置验证规则
|
20
|
+
*/
|
21
|
+
type ValidationOptions = {
|
22
|
+
[section: string]: Record<string, ValidationRule>;
|
23
|
+
};
|
24
|
+
|
25
|
+
/**
|
26
|
+
* 获取字段值
|
27
|
+
* @param section body部分
|
28
|
+
* @param field 字段名
|
29
|
+
* @param req 请求体
|
30
|
+
* @returns 返回字段值
|
31
|
+
*/
|
32
|
+
function getValue(section: string, field: string, req: ProcessRequest):string|null|number|boolean{
|
33
|
+
let value= null;
|
34
|
+
switch (section) {
|
35
|
+
case 'query':
|
36
|
+
value = req.query[field];
|
37
|
+
break;
|
38
|
+
case 'params':
|
39
|
+
value = req.params[field];
|
40
|
+
break;
|
41
|
+
case 'body':
|
42
|
+
value = req.body.fields[field];
|
43
|
+
break;
|
44
|
+
default:
|
45
|
+
break;
|
46
|
+
}
|
47
|
+
return value;
|
48
|
+
}
|
49
|
+
|
50
|
+
/**
|
51
|
+
*
|
52
|
+
*/
|
53
|
+
|
54
|
+
function setValue(section: string, field: string, value: number|boolean|string, req: ProcessRequest): void{
|
55
|
+
switch (section) {
|
56
|
+
case 'body':
|
57
|
+
req.body.fields[field] = value;
|
58
|
+
break;
|
59
|
+
case 'query':
|
60
|
+
req.query[field] = value;
|
61
|
+
break;
|
62
|
+
case 'params':
|
63
|
+
req.params[field] = value;
|
64
|
+
break;
|
65
|
+
default:
|
66
|
+
break;
|
67
|
+
}
|
68
|
+
}
|
69
|
+
/**
|
70
|
+
* 参数验证中间件工厂函数
|
71
|
+
* @param options 验证配置
|
72
|
+
* @returns 返回一个中间件函数
|
73
|
+
*/
|
74
|
+
export const validation = (options: ValidationOptions) => {
|
75
|
+
return (req:http.IncomingMessage, res:http.ServerResponse) => {
|
76
|
+
const request=req as ProcessRequest;
|
77
|
+
const errors: string[] = [];
|
78
|
+
// 遍历每个需要校验的部分(body、query、params)
|
79
|
+
for (const [section, fields] of Object.entries(options)) {
|
80
|
+
let data= null;
|
81
|
+
switch (section){
|
82
|
+
case 'query':
|
83
|
+
data = request.query;
|
84
|
+
break;
|
85
|
+
case 'body':
|
86
|
+
data = request.body.fields;
|
87
|
+
break;
|
88
|
+
case 'params':
|
89
|
+
data = request.params;
|
90
|
+
break;
|
91
|
+
default:
|
92
|
+
errors.push(`Invalid section: ${section}`);
|
93
|
+
return;
|
94
|
+
}
|
95
|
+
|
96
|
+
|
97
|
+
if (!data) {
|
98
|
+
errors.push(`Invalid request section: ${section}`)
|
99
|
+
break;
|
100
|
+
}
|
101
|
+
|
102
|
+
// 遍历每个字段规则
|
103
|
+
for (const [field, rules] of Object.entries(fields)) {
|
104
|
+
|
105
|
+
let value= getValue(section, field, request);
|
106
|
+
|
107
|
+
|
108
|
+
// 判断是否为必填字段
|
109
|
+
if (rules.required === true && value === null) {
|
110
|
+
errors.push(`"${field}" is required in ${section}`);
|
111
|
+
continue;
|
112
|
+
}
|
113
|
+
|
114
|
+
// 如果是可选字段且未提供,则跳过后续检查
|
115
|
+
if (rules.optional === true && value === null) {
|
116
|
+
continue;
|
117
|
+
}
|
118
|
+
// ======【关键改进】自动类型转换(仅 query / params)======
|
119
|
+
if ((section === 'query' || section === 'params') && value !== null) {
|
120
|
+
if (rules.type === 'number') {
|
121
|
+
const num = parseFloat(typeof value === "string" ? value :'error');
|
122
|
+
if (!isNaN(num)) {
|
123
|
+
setValue(section, field, num, request) // 写回原始对象
|
124
|
+
}else{
|
125
|
+
errors.push(`"${field}" must be a number in ${section} your's is ${value}`);
|
126
|
+
}
|
127
|
+
} else if (rules.type === 'boolean') {
|
128
|
+
if (value === 'true') {
|
129
|
+
setValue(section, field, true, request)
|
130
|
+
} else if (value === 'false') {
|
131
|
+
setValue(section, field, false, request);
|
132
|
+
}else{
|
133
|
+
errors.push(`"${field}" must be a boolean in ${section}`);
|
134
|
+
}
|
135
|
+
}
|
136
|
+
}
|
137
|
+
|
138
|
+
// 字符串长度校验
|
139
|
+
if (typeof value === 'string') {
|
140
|
+
if (rules.min !== undefined && value.length < rules.min) {
|
141
|
+
errors.push(`"${field}" must be at least ${rules.min} characters long`);
|
142
|
+
}
|
143
|
+
if (rules.max !== undefined && value.length > rules.max) {
|
144
|
+
errors.push(`"${field}" must be at most ${rules.max} characters long`);
|
145
|
+
}
|
146
|
+
}
|
147
|
+
|
148
|
+
// 格式校验(如 email)
|
149
|
+
if (rules.format === 'email'&& value !== null) {
|
150
|
+
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
151
|
+
if (!emailRegex.test(typeof value === "string" ? value :'error')) {
|
152
|
+
errors.push(`"${field}" must be a valid email address`);
|
153
|
+
}
|
154
|
+
}
|
155
|
+
}
|
156
|
+
}
|
157
|
+
|
158
|
+
// 如果有错误,返回错误
|
159
|
+
if (errors.length > 0) {
|
160
|
+
res.writeHead(400, { 'Content-Type': 'application/json' })
|
161
|
+
res.end(JSON.stringify({ message: '参数校验失败', errors }))
|
162
|
+
console.log(`[${formatLocalTime()}] 参数校验失败: ${errors.join(', ')}`)
|
163
|
+
return true
|
164
|
+
}
|
165
|
+
|
166
|
+
// 否则继续下一个中间件
|
167
|
+
return false
|
168
|
+
};
|
169
|
+
};
|
Binary file
|
@@ -0,0 +1,51 @@
|
|
1
|
+
// routes/index.js
|
2
|
+
import app from '../lib/app.js'
|
3
|
+
import { index, uploadFiles, userDetail } from '../controllers/index.js';
|
4
|
+
import {requestLogger,responseLogger} from '../lib/middleware/logger.js'
|
5
|
+
import {validation} from '../lib/middleware/validate.js'
|
6
|
+
import {staticResources} from '../lib/middleware/static-resources.js'
|
7
|
+
import {cors} from '../lib/middleware/cors.js'
|
8
|
+
import {bodyParser} from '../lib/middleware/body-parser.js'
|
9
|
+
app.beforeRequest(requestLogger)
|
10
|
+
app.beforeRequest(staticResources())
|
11
|
+
app.beforeRequest(cors({
|
12
|
+
origin: ['http://localhost:300', 'https://www.bilibili.com'],
|
13
|
+
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
|
14
|
+
allowedHeaders: ['Content-Type', 'Authorization'],
|
15
|
+
credentials: true // 如果需要跨域带 cookie,设为 true
|
16
|
+
}))
|
17
|
+
|
18
|
+
app.beforeRequest(bodyParser)
|
19
|
+
app.beforeRequest(responseLogger)
|
20
|
+
|
21
|
+
app.get('/', index)
|
22
|
+
app.get('/user/:id', userDetail,[validation({
|
23
|
+
params: {
|
24
|
+
id: {
|
25
|
+
type: 'number',
|
26
|
+
required: true
|
27
|
+
}
|
28
|
+
}
|
29
|
+
})])
|
30
|
+
|
31
|
+
app.post('/uploadFiles', uploadFiles)
|
32
|
+
|
33
|
+
|
34
|
+
import {GroupRoute} from '../lib/GroupRoute.js'
|
35
|
+
const groupRouter=new GroupRoute('/route1')
|
36
|
+
|
37
|
+
app.registerGroupRoute(groupRouter)
|
38
|
+
|
39
|
+
console.log('Routes loaded.');
|
40
|
+
|
41
|
+
//
|
42
|
+
// app.use(loggerMiddleware); // 日志记录
|
43
|
+
// app.use(corsMiddleware); // CORS 控制
|
44
|
+
// app.use(bodyLimitMiddleware); // 请求体大小限制
|
45
|
+
// app.use(bodyParserMiddleware); // 请求体解析
|
46
|
+
// app.use(authMiddleware); // 身份认证
|
47
|
+
// app.use(validationMiddleware); // 参数校验
|
48
|
+
// app.use(staticMiddleware); // 静态资源服务
|
49
|
+
// app.use(router); // 路由分发
|
50
|
+
// app.use(errorLoggerMiddleware); // 错误日志记录
|
51
|
+
// app.use(errorHandlerMiddleware); // 错误统一处理
|
@@ -0,0 +1,11 @@
|
|
1
|
+
import { readFileSync } from 'fs';
|
2
|
+
import path from 'path';
|
3
|
+
import { fileURLToPath } from "url";
|
4
|
+
// 获取当前模块文件路径
|
5
|
+
const __filename = fileURLToPath(import.meta.url);
|
6
|
+
const __dirname = path.dirname(__filename);
|
7
|
+
export default {
|
8
|
+
cert: readFileSync(path.join(__dirname, '../../keys/cert.pem')),
|
9
|
+
key: readFileSync(path.join(__dirname, '../../keys/key.pem'))
|
10
|
+
};
|
11
|
+
console.log('certs loaded');
|