Added multi socket support

This commit is contained in:
Ashutosh Chaudhary 2017-11-17 23:46:30 +05:30
parent 57887ea0a1
commit 8fa80e147c
2 changed files with 67 additions and 8 deletions

View file

@ -9,7 +9,14 @@ export default {
let observer = new Observer(connection, store)
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(){

View file

@ -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{
} 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;
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(){