Created
October 31, 2016 14:04
-
-
Save i-van/be397cebf154bc0541c974193c6ee4e3 to your computer and use it in GitHub Desktop.
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
import { snakeCase } from 'lodash'; | |
export interface IWebSocketMessage { | |
command: string; | |
data: string; | |
} | |
export class WebSocketClient { | |
private client: WebSocket; | |
constructor(url: string, private dispatch: (message) => void) { | |
this.client = new WebSocket(url); | |
this.client.addEventListener('open', this.onOpen); | |
this.client.addEventListener('message', this.onMessage); | |
this.client.addEventListener('close', this.onClose); | |
} | |
// @todo | |
private onOpen = (event) => { | |
console.log('onOpen'); | |
console.log(event); | |
}; | |
private onMessage = (event: MessageEvent) => { | |
const message: IWebSocketMessage = JSON.parse(event.data); | |
this.dispatch({ | |
type: snakeCase(message.command).toUpperCase(), | |
payload: message.data, | |
}); | |
}; | |
// @todo | |
private onClose = (event) => { | |
console.log('onClose'); | |
console.log(event); | |
console.log(event.wasClean, event.code, event.reason); | |
}; | |
public send(message: IWebSocketMessage) { | |
this.client.send(JSON.stringify(message)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment