Skip to content

Instantly share code, notes, and snippets.

@kenreilly
Last active September 15, 2023 20:54
Show Gist options
  • Save kenreilly/131c847983af274b764a2bdcdac311ab to your computer and use it in GitHub Desktop.
Save kenreilly/131c847983af274b764a2bdcdac311ab to your computer and use it in GitHub Desktop.
Shared WebSocket message class
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