Last active
December 3, 2018 09:39
-
-
Save okwolf/0804cf2b3be5bf994eee7ceda39977d1 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
const randomEffect = (props, dispatch) => { | |
const randomValue = Math.random() * (props.max - props.min) + props.min; | |
dispatch(props.action, randomValue) | |
}; | |
export const Random = ({ action, min = 0, max = 1 }) => ({ | |
props: { | |
action, | |
min, | |
max | |
}, | |
effect: randomEffect | |
}); | |
const httpEffect = (props, dispatch) => { | |
fetch(props.url, props) | |
.then(function(response) { | |
if (!response.ok) { | |
throw response; | |
} | |
return response; | |
}) | |
.then(function(response) { | |
return response[props.response](); | |
}) | |
.then(function(result) { | |
dispatch(props.action, result); | |
}) | |
.catch(function(error) { | |
dispatch(props.error, error); | |
}); | |
}; | |
export const Http = options => ({ | |
props: { | |
response: "json", | |
error: options.action, | |
...options | |
}, | |
effect: httpEffect | |
}); | |
const webSocketEffect = (props, dispatch) => { | |
const socket = new WebSocket(props.url); | |
if (props.onOpenMessage) { | |
socket.onopen = () => { | |
socket.send(props.onOpenMessage); | |
}; | |
} | |
socket.onmessage = dispatch.bind(null, props.action); | |
return () => { | |
socket.close(); | |
}; | |
}; | |
export const WebSocketClient = props => ({ | |
props, | |
effect: webSocketEffect | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment