diff --git a/src/Main.js b/src/Main.js index f19a820..d222143 100755 --- a/src/Main.js +++ b/src/Main.js @@ -9,7 +9,14 @@ export default { let observer = new Observer(connection, store) - Vue.prototype.$socket = observer.Socket; + if(typeof connection == 'object'){ + Vue.prototype.$socket = [] + Object.keys(connection).forEach(key => { + Vue.prototype.$socket[key] = observer.Sockets[key]; + }) + }else{ + Vue.prototype.$socket = observer.Socket; + } Vue.mixin({ created(){ diff --git a/src/Observer.js b/src/Observer.js index e1afdcc..a535843 100755 --- a/src/Observer.js +++ b/src/Observer.js @@ -4,17 +4,69 @@ import Socket from 'socket.io-client' export default class{ constructor(connection, store) { + this.Sockets = null - if(typeof connection == 'string'){ - this.Socket = Socket(connection); - }else{ - this.Socket = connection - } + if(typeof connection == 'string'){ + this.Socket = Socket(connection); + } else if(typeof connection == 'object') { + this.Sockets = [] + Object.keys(connection).forEach(key => { + this.Sockets[key] = Socket(connection[key]); + }); + } else{ + this.Socket = connection + } - if(store) this.store = store; + if(store) this.store = store; - this.onEvent() + (this.Sockets) ? this.onEvents() : this.onEvent() + } + + onEvents(){ + for(let socket in this.Sockets){ + this.onEventWithKey(this.Sockets[socket], socket) + } + } + + onEventWithKey(socket, key){ + var super_onevent = socket.onevent; + socket.onevent = (packet) => { + super_onevent.call(socket, packet); + + Emitter.emit(packet.data[0], packet.data[1]); + + if(this.store) this.passToStoreWithKey(key.toUpperCase()+'_SOCKET_'+packet.data[0], [ ...packet.data.slice(1)], key) + }; + + let _this = this; + + ["connect", "error", "disconnect", "reconnect", "reconnect_attempt", "reconnecting", "reconnect_error", "reconnect_failed", "connect_error", "connect_timeout", "connecting", "ping", "pong"] + .forEach((value) => { + socket.on(value, (data) => { + Emitter.emit(value, data); + if(_this.store) _this.passToStoreWithKey(key.toUpperCase()+'_SOCKET_'+value, data, key) + }) + }) + } + + passToStoreWithKey(event, payload, key){ + if(!event.startsWith(key.toUpperCase()+'_SOCKET_')) return + for(let namespaced in this.store._mutations) { + let mutation = namespaced.split('/').pop() + if(mutation === event.toUpperCase()) this.store.commit(namespaced, payload) + } + + for(let namespaced in this.store._actions) { + let action = namespaced.split('/').pop() + if(!action.startsWith(key+'_socket_')) continue + + let camelcased = key+'_socket_'+event + .replace(key.toUpperCase()+'_SOCKET_', '') + .replace(/^([A-Z])|[\W\s_]+(\w)/g, (match, p1, p2) => p2 ? p2.toUpperCase() : p1.toLowerCase()) + + if(action === camelcased) this.store.dispatch(namespaced, payload) + } } onEvent(){