refactor: v2 重构 — 模块化拆分 + AI Prompt模板化 + 前端状态管理
P0 - AI交互层:
- ai/prompt.js: 模块化 Prompt 模板
- ai/validator.js: JSON Schema 校验 + normalize
- ai/client.js: DeepSeek API 封装
- 金额计算唯一化,时间格式归一化
P1 - 后端架构:
- routes/: auth/rooms/messages/purchases 独立路由
- middleware/auth.js: 认证授权中间件
- ws/index.js: WebSocket 连接管理
- db.js: 启用 foreign_keys
- server.js: 从588行精简到40行入口
P2 - 前端架构:
- public/css/style.css: CSS 独立
- public/js/store.js: 全局状态 Store
- public/js/{chat,ws,purchases,auth}.js: 功能模块拆分
- index.html: 纯 HTML 结构, v2.6
This commit is contained in:
56
server/ws/index.js
Normal file
56
server/ws/index.js
Normal file
@@ -0,0 +1,56 @@
|
||||
// WebSocket 管理模块
|
||||
const jwt = require('jsonwebtoken');
|
||||
const ADMINS = (process.env.ADMINS || '').split(',').map(s => s.trim()).filter(Boolean);
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'xiaocai-secret-2024';
|
||||
|
||||
const clients = new Map();
|
||||
|
||||
function init(wss) {
|
||||
wss.on('connection', (ws, req) => {
|
||||
console.log('✅ WebSocket 客户端已连接');
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
const token = url.searchParams.get('token');
|
||||
if (!token) return ws.close();
|
||||
|
||||
let username;
|
||||
try { const decoded = jwt.verify(token, JWT_SECRET); username = decoded.username; }
|
||||
catch (e) { return ws.close(); }
|
||||
|
||||
ws.username = username;
|
||||
ws.isAdmin = ADMINS.includes(username);
|
||||
clients.set(ws, { username, roomId: null, isAdmin: ws.isAdmin });
|
||||
|
||||
ws.on('message', (data) => {
|
||||
try {
|
||||
const msg = JSON.parse(data);
|
||||
if (msg.type === 'join') {
|
||||
ws.roomId = msg.roomId;
|
||||
clients.set(ws, { username, roomId: msg.roomId, isAdmin: ws.isAdmin });
|
||||
}
|
||||
} catch (e) {}
|
||||
});
|
||||
|
||||
ws.on('close', () => clients.delete(ws));
|
||||
});
|
||||
}
|
||||
|
||||
function broadcastToRoomExcludeSelf(roomId, excludeUsername, data) {
|
||||
const message = JSON.stringify(data);
|
||||
clients.forEach((info, ws) => {
|
||||
if (info.roomId === roomId && info.username !== excludeUsername && ws.readyState === 1) ws.send(message);
|
||||
});
|
||||
}
|
||||
|
||||
function broadcastToRoom(roomId, data) {
|
||||
const message = JSON.stringify(data);
|
||||
clients.forEach((info, ws) => {
|
||||
if (info.roomId === roomId && ws.readyState === 1) ws.send(message);
|
||||
});
|
||||
}
|
||||
|
||||
function broadcast(data) {
|
||||
const message = JSON.stringify(data);
|
||||
clients.forEach((info, ws) => { if (ws.readyState === 1) ws.send(message); });
|
||||
}
|
||||
|
||||
module.exports = { init, broadcastToRoomExcludeSelf, broadcastToRoom, broadcast };
|
||||
Reference in New Issue
Block a user