function newUUID () { /* eslint-disable */ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = Math.random() * 16 | 0, v = c === 'x' ? r : r & 0x3 | 0x8; return v.toString(16); }); /* eslint-enable */ } const store = new Vuex.Store({ state: { socket: { _session: localStorage.getItem('session'), isConnected: false, reconnectError: false, eventMSGID: {}, eventTo: {}, }, controller: { _ap : {}, ap: [], _clients: [], clients: {}, }, }, mutations:{ SOCKET_ONOPEN (state, event) { state.socket.isConnected = true }, SOCKET_ONCLOSE (state, event) { state.socket.isConnected = false }, SOCKET_ONERROR (state, event) { console.error(state, event) }, // default handler called for all methods SOCKET_ONMESSAGE (state, msg) { if (msg.subject === 'session_init') { if (state.socket._session === null) { state.socket._session = newUUID(); localStorage.setItem('session', state.socket._session); } msg.id = state.socket._session; Vue.prototype.$socket.sendObj(msg); return; } const msgFunc = state.socket.eventMSGID[msg.id]; if (msgFunc) { msgFunc(state, msg); delete state.socket.eventMSGID[msg.id]; return; } const eventFuncs = state.socket.eventTo[msg.subject]; if (typeof eventFuncs === 'object' && eventFuncs.length > 0) { for (const key in eventFuncs) { const func = eventFuncs[key]; if (func) { func(state, msg); } } return; } console.log(`unable to identify message: ${msg.subject}`); }, // mutations for reconnect methods SOCKET_RECONNECT(state, count) { console.info(state, "reconnect:", count) }, SOCKET_RECONNECT_ERROR(state) { state.socket.reconnectError = true; }, setEvent (state, data) { state.socket.eventTo[data.subject] = [data.callback]; }, addEvent (state, data) { if (typeof state.socket.eventTo[data.subject] !== 'object') { state.socket.eventTo[data.subject] = []; } state.socket.eventTo[data.subject].push(data.callback); }, delEvent (state, data) { if (typeof state.socket.eventTo[data.subject] === 'object' && state.socket.eventTo[data.subject].length > 1) { state.socket.eventTo[data.subject].pop(data.callback); } else { state.socket.eventTo[data.subject] = []; } }, call (state, data) { if (!data.msg.id) { data.msg.id = newUUID(); } const ret = Vue.prototype.$socket.sendObj(data.msg); if (typeof data.callback === 'function') { state.socket.eventMSGID[data.msg.id] = data.callback; } return ret; } } })