Skip to content

Instantly share code, notes, and snippets.

@i-van
Created October 31, 2016 14:04
Show Gist options
  • Save i-van/be397cebf154bc0541c974193c6ee4e3 to your computer and use it in GitHub Desktop.
Save i-van/be397cebf154bc0541c974193c6ee4e3 to your computer and use it in GitHub Desktop.
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