Last active
September 15, 2023 20:54
-
-
Save kenreilly/131c847983af274b764a2bdcdac311ab to your computer and use it in GitHub Desktop.
Shared WebSocket message class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export enum WebSocketMessageType { | |
PING = 'ping', | |
ECHO = 'echo' | |
} | |
export class WebSocketMessage { | |
public msg_type: WebSocketMessageType | |
public data: Object | |
constructor(msg_type: WebSocketMessageType, data: Object) { | |
this.msg_type = msg_type | |
this.data = data | |
} | |
public static parse(message: string): WebSocketMessage { | |
try { | |
let x: Object = JSON.parse(message) | |
return new WebSocketMessage(x['msg_type'], x['data'] ?? {}) | |
} | |
catch (e) { console.log(e) } | |
} | |
public toString() { | |
return JSON.stringify({ msg_type: this.msg_type, data: this.data }) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment