import io from 'socket.io-client'; import 'register-packets'; import SocketIoParser from '...packet'; let socket = null; function onMessageConnect({address, options}) { socket = io(address, { parser: SocketIoParser, ...options, }); const onSocketConnect = () => { postMessage({ type: 'emit', payload: ['connect'], }); } const onSocketConnectError = (error) => { postMessage({ type: 'emit', payload: ['connect_error', error.toString()], }); } const onSocketConnectTimeout = (timeout) => { postMessage({ type: 'emit', payload: ['connect_timeout', timeout], }); } const onSocketDisconnect = (reason) => { postMessage({ type: 'emit', payload: ['disconnect', reason], }); } const onSocketError = (error) => { postMessage({ type: 'emit', payload: ['error', error.toString()], }); } const onSocketReconnect = (attempt) => { postMessage({ type: 'emit', payload: ['reconnect', attempt], }); } const onSocketReconnectAttempt = (attempt) => { postMessage({ type: 'emit', payload: ['reconnect_attempt', attempt], }); } const onSocketReconnecting = (attempt) => { postMessage({ type: 'emit', payload: ['reconnecting', attempt], }); } const onSocketReconnectError = (error) => { postMessage({ type: 'emit', payload: ['reconnect_error', error.toString()], }); } const onSocketReconnectFailed = () => { postMessage({ type: 'emit', payload: ['reconnect_failed'], }); } const onSocketPing = () => { postMessage({ type: 'emit', payload: ['ping'], }); } const onSocketPong = (latency) => { postMessage({ type: 'emit', payload: ['pong', latency], }); } socket.on('connect', onSocketConnect); socket.on('connect_error', onSocketConnectError); socket.on('connect_timeout', onSocketConnectTimeout); socket.on('disconnect', onSocketDisconnect); socket.on('error', onSocketError); socket.on('reconnect', onSocketReconnect); socket.on('reconnect_attempt', onSocketReconnectAttempt); socket.on('reconnecting', onSocketReconnecting); socket.on('reconnect_error', onSocketReconnectError); socket.on('reconnect_failed', onSocketReconnectFailed); socket.on('ping', onSocketPing); socket.on('pong', onSocketPong); } function onMessageClose() { if (!socket) { return; } socket.close(); socket = undefined; } function onMessageEmit(args) { if (!socket) { return; } socket.binary(true).emit(...args); } function onMessageOn(type) { if (!socket) { return; } if (socket.listeners(type).length !== 0) { return; } socket.on(type, function(...args) { postMessage({ type: 'emit', payload: [type].concat(args), }); }); } self.onmessage = function({data: action}) { switch(action.type) { case 'connect': return onMessageConnect(action.payload); case 'emit': return onMessageEmit(action.payload); case 'on': return onMessageOn(action.payload); case 'close': return onMessageClose(); } }