Files
mayfly-go/mayfly_go_web/src/common/syssocket.ts

108 lines
2.9 KiB
TypeScript
Raw Normal View History

import Config from './config';
import { ElNotification } from 'element-plus';
import SocketBuilder from './SocketBuilder';
import { getToken } from '@/common/utils/storage';
import { joinClientParams } from './request';
class SysSocket {
/**
* socket连接
*/
socket: any;
/**
* key -> value ->
*/
categoryHandlers: Map<string, any> = new Map();
/**
*
*/
messageTypes = {
0: 'error',
1: 'success',
2: 'info',
};
/**
* websocket
*/
init() {
// 存在则不需要重新建立连接
if (this.socket) {
return;
}
const token = getToken();
if (!token) {
return null;
}
2023-10-20 21:31:46 +08:00
console.log('init system ws');
const sysMsgUrl = `${Config.baseWsUrl}/sysmsg?${joinClientParams()}`;
this.socket = SocketBuilder.builder(sysMsgUrl)
.message((event: { data: string }) => {
2023-12-27 19:55:36 +08:00
let message;
try {
message = JSON.parse(event.data);
} catch (e) {
console.error('解析ws消息失败', e);
return;
}
// 存在消息类别对应的处理器,则进行处理,否则进行默认通知处理
const handler = this.categoryHandlers.get(message.category);
if (handler) {
handler(message);
return;
}
const type = this.getMsgType(message.type);
ElNotification({
duration: 0,
title: message.title,
message: message.msg,
type: type,
});
})
.open((event: any) => console.log(event))
.close(() => {
console.log('close sys socket');
this.socket = null;
})
.build();
}
destory() {
2023-12-28 17:21:33 +08:00
this.socket?.close();
this.socket = null;
2023-12-28 17:21:33 +08:00
this.categoryHandlers?.clear();
}
/**
*
*
* @param category
* @param handlerFunc
*/
registerMsgHandler(category: any, handlerFunc: any) {
2023-10-20 21:31:46 +08:00
this.init();
if (this.categoryHandlers.has(category)) {
console.log(`${category}该类别消息处理器已存在...`);
return;
}
if (typeof handlerFunc != 'function') {
throw new Error('message handler需为函数');
}
this.categoryHandlers.set(category, handlerFunc);
}
getMsgType(msgType: any) {
return this.messageTypes[msgType];
}
}
// 全局系统消息websocket;
const sysSocket = new SysSocket();
export default sysSocket;