Created
August 4, 2017 17:57
-
-
Save typehorror/0403650701ded86cddb0046de0cfb78b 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 { 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