Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { Component } from "react";
import { connect } from "react-redux";
import { getTicket, getAssignedTickets } from "../../actions";
import { getJWToken } from "../../middleware/api";
class Socket extends Component {
getWebsocketServerLocation() {
const host = window.document.location.host.replace(/:.*/, "");
return "ws://" + host + ":8010";
}
onOpen = () => {
console.debug("Connection established");
};
onMessage = msg => {
const payload = JSON.parse(msg.data);
if(payload.type === "auth")
this.sendAuth();
else if (payload.organization_id === this.props.organizationId)
payload.objects.forEach(this.eventReceived);
};
eventReceived = ({type, action, ids}) => {
this.props.onReceiveEvent(type, action, ids)
};
sendAuth = () => {
const msg = {
organizationId: this.props.organizationId,
JWT: getJWToken(),
};
this.ws.send(JSON.stringify(msg));
};
onClose = () => {
if (!this.autoReconnect) return;
console.debug("Connection lost");
setTimeout(this.connect, 5000);
};
connect = () => {
this.autoReconnect = true;
this.ws = new WebSocket(this.getWebsocketServerLocation());
this.ws.onopen = this.onOpen;
this.ws.onmessage = this.onMessage;
this.ws.onclose = this.onClose;
};
close = () => {
this.ws.close();
};
componentWillUnmount() {
this.autoReconnect = false;
this.close();
}
componentWillMount() {
this.connect();
}
render() {
return null;
}
}
export default connect(null, { getTicket, getAssignedTickets })(Socket);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment