Created
April 10, 2017 15:22
-
-
Save mishitpatel/7ace64d07574109a152f806625a8929c to your computer and use it in GitHub Desktop.
websockets with csrf
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 React, { Component } from 'react' | |
const { API } = process.env | |
import * as io from 'socket.io-client' | |
import { connect } from 'react-redux' | |
import { broadcastControllerOnline, broadcastControllerOffline, broadcastNewActivityFound } from 'actions/LiveEvents' | |
import getUserAccountFromState from 'utils/getUserAccountFromState' | |
import cookies from 'cookies-js'; | |
// | |
// Grab csrf_token from cookies to put it in a custom header | |
// | |
const csrfToken = cookies.get('csrf_token'); | |
const socket = io.connect(API.socket, { | |
transports: ['websocket'], | |
extraHeaders: { | |
'x-csrf-token': csrfToken || '' | |
}}) | |
class Socket extends Component{ | |
constructor(props){ | |
super(props) | |
} | |
// | |
// We never need to re-render this component once is active | |
// | |
shouldComponentUpdate() { | |
return false | |
} | |
// | |
// Before the component gets mounted we send the property id to the socket | |
// and we start listening to some important events: | |
// | |
// CONTROLLER_OFFLINE: When one of the controller goes down | |
// | |
// CONTROLLER_ONLINE: When one of the controller it's back online | |
// | |
// NEW_ACTIVITY_FOUND: When there is new activity for the Activity view | |
// | |
componentWillMount() { | |
const { dispatch, userAccount } = this.props | |
// | |
// Every time the socket gets connected we emit the property id | |
// this means that if for some reason the socket gets disconnected and | |
// then reconnects we send back again the property id and keep listening | |
// | |
socket.on('connect', function(){ | |
socket.emit('new_room', userAccount.property.id) | |
}) | |
socket.on('CONTROLLER_OFFLINE', function(data){ | |
dispatch(broadcastControllerOffline()) | |
}) | |
socket.on('CONTROLLER_ONLINE', function(data){ | |
dispatch(broadcastControllerOnline()) | |
}) | |
socket.on('NEW_ACTIVITY_FOUND', function(data){ | |
dispatch(broadcastNewActivityFound()) | |
}) | |
socket.on('disconnect', function(){ }) | |
} | |
render() { | |
return false | |
} | |
} | |
const mapStateToProps = (state) => { | |
const userAccount = getUserAccountFromState(state) | |
return { userAccount } | |
} | |
export default connect(mapStateToProps)(Socket) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment