style(zulip): 优化zulip业务模块代码规范

范围:src/business/zulip/
- 统一命名规范和注释格式
- 完善JSDoc注释和参数说明
- 优化代码结构和缩进
- 清理未使用的导入和变量
- 更新修改记录和版本信息
This commit is contained in:
moyin
2026-01-12 19:42:38 +08:00
parent 03f0cd6bab
commit efac782243
6 changed files with 329 additions and 50 deletions

View File

@@ -69,9 +69,24 @@ export class CleanWebSocketGateway implements OnModuleInit, OnModuleDestroy {
}
});
ws.on('close', () => {
this.logger.log(`WebSocket连接关闭: ${ws.id}`);
this.cleanupClient(ws);
ws.on('close', (code, reason) => {
this.logger.log(`WebSocket连接关闭: ${ws.id}`, {
code,
reason: reason?.toString(),
authenticated: ws.authenticated,
username: ws.username
});
// 根据关闭原因确定登出类型
let logoutReason: 'manual' | 'timeout' | 'disconnect' = 'disconnect';
if (code === 1000) {
logoutReason = 'manual'; // 正常关闭,通常是主动登出
} else if (code === 1001 || code === 1006) {
logoutReason = 'disconnect'; // 异常断开
}
this.cleanupClient(ws, logoutReason);
});
ws.on('error', (error) => {
@@ -110,6 +125,9 @@ export class CleanWebSocketGateway implements OnModuleInit, OnModuleDestroy {
case 'login':
await this.handleLogin(ws, message);
break;
case 'logout':
await this.handleLogout(ws, message);
break;
case 'chat':
await this.handleChat(ws, message);
break;
@@ -166,6 +184,38 @@ export class CleanWebSocketGateway implements OnModuleInit, OnModuleDestroy {
}
}
/**
* 处理主动登出请求
*/
private async handleLogout(ws: ExtendedWebSocket, message: any) {
try {
if (!ws.authenticated) {
this.sendError(ws, '用户未登录');
return;
}
this.logger.log(`用户主动登出: ${ws.username} (${ws.id})`);
// 调用ZulipService处理登出标记为主动登出
await this.zulipService.handlePlayerLogout(ws.id, 'manual');
// 清理WebSocket状态
this.cleanupClient(ws);
this.sendMessage(ws, {
t: 'logout_success',
message: '登出成功'
});
// 关闭WebSocket连接
ws.close(1000, '用户主动登出');
} catch (error) {
this.logger.error('登出处理失败', error);
this.sendError(ws, '登出处理失败');
}
}
private async handleChat(ws: ExtendedWebSocket, message: any) {
try {
if (!ws.authenticated) {
@@ -318,14 +368,34 @@ export class CleanWebSocketGateway implements OnModuleInit, OnModuleDestroy {
}
}
private cleanupClient(ws: ExtendedWebSocket) {
// 从地图房间中移除
if (ws.currentMap) {
this.leaveMapRoom(ws.id, ws.currentMap);
private async cleanupClient(ws: ExtendedWebSocket, reason: 'manual' | 'timeout' | 'disconnect' = 'disconnect') {
try {
// 如果用户已认证调用ZulipService处理登出
if (ws.authenticated && ws.id) {
this.logger.log(`清理已认证用户: ${ws.username} (${ws.id})`, { reason });
await this.zulipService.handlePlayerLogout(ws.id, reason);
}
// 从地图房间中移除
if (ws.currentMap) {
this.leaveMapRoom(ws.id, ws.currentMap);
}
// 从客户端列表中移除
this.clients.delete(ws.id);
this.logger.log(`客户端清理完成: ${ws.id}`, {
reason,
wasAuthenticated: ws.authenticated,
username: ws.username
});
} catch (error) {
this.logger.error(`清理客户端失败: ${ws.id}`, {
error: (error as Error).message,
reason,
username: ws.username
});
}
// 从客户端列表中移除
this.clients.delete(ws.id);
}
private generateClientId(): string {