Last active
October 27, 2020 11:08
-
-
Save miraklez/1257aac9808f98e334dcfdb0aae7fe10 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
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
// Available variables: | |
// - Machine | |
// - interpret | |
// - assign | |
// - send | |
// - sendParent | |
// - spawn | |
// - raise | |
// - actions | |
// - XState (all XState exports) | |
const socketInvoke = | |
(ctx) => (callback, onReceive) => { | |
try { | |
const { url, protocols } = ctx.options | |
ctx.socket = new WebSocket(url, protocols); | |
ctx.socket.onopen = () => { | |
console.log(`[WebSocket::OPEN]`); | |
callback('SUCCESS'); | |
} | |
ctx.socket.onclose = ({ code, reason, wasClean }) => { | |
console.log(`[WebSocket::CLOSE]`); | |
console.table({code, reason, wasClean}); | |
callback({ type: 'CLOSE', code, reason, wasClean}); | |
} | |
ctx.socket.onmessage = ({data}) => { | |
console.log(`[WebSocket::MESSAGE]`, data); | |
} | |
ctx.socket.onerror = (event) => { | |
console.log(`[WebSocket::ERROR]`, event); | |
} | |
} catch (err) { | |
console.log(`[WebSocket::EXCEPTIONS]`, err) | |
} | |
} | |
const websocketMachine = Machine({ | |
id: 'websocket', | |
initial: 'idle', | |
context: { | |
options: {}, | |
socket: undefined | |
}, | |
states: { | |
idle: { | |
on: { | |
OPEN: { | |
target: 'connecting', | |
cond: 'isURL', | |
actions: 'setWebSocketOptions' | |
} | |
} | |
}, | |
connecting: { | |
invoke: { | |
id: 'socket', | |
src: socketInvoke | |
}, | |
on: { | |
SUCCESS: 'connected', | |
CLOSE: [ | |
{ | |
target: 'idle', | |
cond: 'isNormalCode' | |
}, | |
{ target: 'failure' } | |
] | |
} | |
}, | |
connected: {}, | |
failure: {} | |
} | |
}, { | |
actions: { | |
setWebSocketOptions: (context, event) => { | |
context.options = { | |
url: event.url, | |
protocols: event.protocols | |
} | |
} | |
}, | |
guards: { | |
isURL: (_, { url }) => { | |
return (typeof url === 'string') && (url.length > 5) | |
}, | |
isNormalCode: (_, event) => { | |
console.log(`isNormalCode`, event); | |
return event.code === 1000 | |
} | |
} | |
}) | |
window.websocketMachine = websocketMachine |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment