Files
CT/src/Model/connectionModel.ts
T

65 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-07-19 17:56:25 +02:00
// this file is responsible for managing UDN connections.
import UDNFrontend, { Message } from "udn-frontend";
2024-07-19 19:47:40 +02:00
import { ChatMessage } from "./chatModel";
2024-07-19 23:45:07 +02:00
import { stringify } from "./Utility/utility";
2024-07-19 17:56:25 +02:00
export default class ConnectionModel {
// basic
udn: UDNFrontend;
// data
get isConnected(): boolean {
return this.udn.ws != undefined && this.udn.ws.readyState == 1;
}
get address(): string | undefined {
2024-07-19 17:56:25 +02:00
return this.udn.ws?.url;
}
// connection
connect = (address: string): void => {
2024-07-19 17:56:25 +02:00
this.udn.connect(address);
};
2024-07-19 17:56:25 +02:00
disconnect = (): void => {
2024-07-19 17:56:25 +02:00
this.udn.disconnect();
};
2024-07-19 17:56:25 +02:00
2024-07-20 02:18:15 +02:00
handleConnectionChange = (): void => {
console.log("connection status:", this.isConnected, this.address);
};
2024-07-19 17:56:25 +02:00
// messaging
sendChatMessage = (chatMessage: ChatMessage): boolean => {
2024-07-19 20:50:42 +02:00
const stringifiedBody: string = stringify(chatMessage);
2024-07-19 17:56:25 +02:00
return this.udn.sendMessage(chatMessage.channel, stringifiedBody);
};
2024-07-19 17:56:25 +02:00
// setup
2024-07-19 18:17:00 +02:00
constructor(configuration: ConnectionModelConfiguration) {
// create frontend
2024-07-19 17:56:25 +02:00
this.udn = new UDNFrontend();
2024-07-19 18:17:00 +02:00
// setup handlers
this.udn.onmessage = (data: Message) => {
configuration.messageHandler(data);
};
this.udn.onconnect = () => {
this.handleConnectionChange();
configuration.connectionChangeHandler();
};
this.udn.ondisconnect = () => {
this.handleConnectionChange();
configuration.connectionChangeHandler();
};
2024-07-19 17:56:25 +02:00
}
}
2024-07-19 18:17:00 +02:00
2024-07-19 19:47:07 +02:00
// types
2024-07-19 18:17:00 +02:00
export interface ConnectionModelConfiguration {
connectionChangeHandler: () => void;
messageHandler: (data: Message) => void;
}