Created
August 18, 2018 23:01
-
-
Save adamschachne/d9bea65ba0db1c26ce3e2bd64a01ce94 to your computer and use it in GitHub Desktop.
Redux WebSocket middleware
This file contains hidden or 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 { Socket } from './Socket'; | |
export const createSocketMiddleware = (host, port) => store => { | |
const socket = new Socket(host, port); | |
socket.onopen = () => { | |
store.dispatch({ type: "SOCKET_OPEN" }); | |
} | |
socket.onclose = () => { | |
store.dispatch({ type: "SOCKET_CLOSED" }); | |
} | |
socket.onmessage = (args) => { | |
let msg; | |
try { | |
console.log(args); | |
msg = JSON.parse(args[0].data); | |
} catch (err) { | |
console.error(err); | |
msg = args[0].data; | |
console.log(args[0], msg); | |
} finally { | |
console.log("got a message: ", msg); | |
store.dispatch({ type: "RECEIVE_MESSAGE", payload: msg }); | |
} | |
} | |
socket.onerror = () => { | |
store.dispatch({ type: "SOCKET_ERROR" }); | |
} | |
return next => action => { | |
if (action.meta && action.meta === "socket") { | |
switch (action.type) { | |
case "CONNECT": { | |
socket.connect(); | |
break; | |
} | |
case "DISCONNECT": { | |
socket.disconnect(); | |
break; | |
} | |
case "SEND_MESSAGE": { | |
socket.send(action.payload); | |
break; | |
} | |
default: break; | |
} | |
} | |
next(action); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
silky smooth