socketcluster-client icon indicating copy to clipboard operation
socketcluster-client copied to clipboard

Question - wrapping sc client

Open happilymarrieddad opened this issue 6 years ago • 2 comments

@jondubois Hey man, if I do this would it cause any issues? I've tested it locally and it works fine. Basically, I'm trying to wrap promises around emit and publish for the client.

Thanks!

import * as SC from 'socketcluster-client'
import * as Emitter from 'component-emitter'

export function install (_Vue,options) {
    function vue2SocketclusterInit() {
        var opts = this.$options

        if (opts.socket) {
            this.$socket = opts.socket
        } else if (opts.parent && opts.parent.$socket) {
            this.$socket = opts.parent.$socket
        } else {
            let soc = SC.connect(options)

            soc.emit = function(event,data,callback) {
                return new Promise((resolve,reject) => {
                    if (soc._localEvents[event] == null) {
                        return soc._emit(event,data,(err,res) => {
                            callback && callback(err,res)
                            if (err) return reject(err)
                            return resolve(res)
                        })
                    }

                    Emitter.prototype.emit.call(soc, event, data)
                })
            }

            soc.publish = function(channelName,data,callback) {
                return new Promise((resolve,reject) => {
                    let pubData = {
                        channel:soc._decorateChannelName(channelName),
                        data
                    }

                    soc._emit('#publish',pubData,(err,res) => {
                        callback && callback(err,res)
                        if (err) return reject(err)
                        return resolve(res)
                    })
                })
            }

            this.$socket = soc
        }

    }

    var usesInit = _Vue.config._lifecycleHooks.indexOf('init') > -1
    _Vue.mixin(usesInit ? { init: vue2SocketclusterInit } : { beforeCreate: vue2SocketclusterInit })
}

happilymarrieddad avatar Apr 09 '18 22:04 happilymarrieddad

Here are the original funcs for quick reference.

SCSocket.prototype.emit = function (event, data, callback) {
  if (this._localEvents[event] == null) {
    this._emit(event, data, callback);
  } else {
    Emitter.prototype.emit.call(this, event, data);
  }
};

SCSocket.prototype.publish = function (channelName, data, callback) {
  var pubData = {
    channel: this._decorateChannelName(channelName),
    data: data
  };
  this.emit('#publish', pubData, callback);
};

happilymarrieddad avatar Apr 09 '18 22:04 happilymarrieddad

I can always do this in a class or something but then I need to pass all the funcs/props to the class.. I don't like doing that.

happilymarrieddad avatar Apr 09 '18 22:04 happilymarrieddad