0

I am currently using Node.js as a server (Express.js) and AngularJs in client side, switched from HTTP-based API to WebSockets (using Socket.io) due for the performance improvement.

Since WebSockets lacks of status codes/errors management and simply returns JSON with an optional callback, I have to implement this error management. I want a consistant behaviour when an error occurs, and instead of making this error check manually I want to wrap it to reduce the boilplate in my code using Promises over the bad old callback-based.

For example instead of using raw socket.io in angular:

socket.emit('users/read', {id: 2}, function handleResponse(res){
    if(res.success){
        var user = res.data;
        socket.emit('projects/by-user', {userId: user.id}, function handleResponse(res){
            if(res.success){
                var projects = res.data;
                // Do something with the data
            } else{
                // Error getting user's projects
                console.log(res.error)
            }
        })
    } else{
        // Error getting user
        console.log(res.error)
    }
})

I would like to have something like this:

webSocketClient
    .request('users/read', {id:2})
    .then(function(user){
        return webSocketClient.request('projects/by-user', {userId: user.id})
    })
    .then(function(projects){
        // Do something with projects
    })
    .catch(function(err){
        // Something went bad
    })

What is the recommended JSON structure when implementing a request-response WebSockets-based API? Or there is a library that can do this for me?

I am currently thinks about a JSON with this structure in response:

{
    success: true/false,
    data: [if exists],
    statusCode: [default 200 for success or 500 for failure],
    error: [if exists]
}

I think that working with WebSockets using Promises instead of callbacks is a fundamental and obious requirement, but for some reason all the libraries I found didn't wrapped the callbacks with Promises, which leads me to the question if I am missing the something?

Thanks

Aviran Cohen
  • 5,581
  • 4
  • 48
  • 75
  • Why not write your own promises? – Jonas Wilms Aug 13 '16 at 10:14
  • Possible duplicate of [How can I use Socket.IO with promises?](http://stackoverflow.com/questions/21768219/how-can-i-use-socket-io-with-promises) – Yan Foto Aug 13 '16 at 10:25
  • @jfriend00 There is a built-in way to support responses/acknowledgements using callbacks, so the tagging won't be required http://socket.io/docs/#sending-and-getting-data-(acknowledgements) – Aviran Cohen Aug 13 '16 at 10:26
  • @JaromandaX First things first - I've already implemented it and I did not ask for it, I just feels I am missing something. Look closer at my questions - I am asking what is the recommended JSON structure and if there is library that fits my case, wondering if I might be wrong using websockets for request-response based API, since it seems there is lack of solutions for this. – Aviran Cohen Aug 13 '16 at 10:31
  • @JaromandaX To be honest I forgot I have access to the source code from this computer, although I think the implementation might be non-relevant, since the issue here is the design and whether a request-response API for websockets (wrapped with Promises) is the right thing or I am trying to do something that should not be done since I failed to find resources and libraries to address this issue. – Aviran Cohen Aug 13 '16 at 10:43

2 Answers2

0
var ownhandler={};
ownhandler.request(query){
o={};
o.query=query;
o.then=function (callback){
    calltheserver(this.query,function(){
      callback();
     }
 };
 return o;
 }

Im not sure if its what you want but now you can do sth like:

ownhandler.request("whatever").then(function(){
 //function finished
 }

However you have to replace the "calltheserver()" with a real function.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

Here is the way I've implemented it so far in the client side (untested), not sure if there is a better library or solution for addressing Websocket based request-response API.

Client Side Code (Angular.js)

angular.module('app.web-sockets', [])
.factory('wsClient', function createWebSocketClient(socket, $q, assert, $timeout) {
    function WebSocketClient(socket) {
        this._socket = socket;
    }

    WebSocketClient.prototype.request = function request(url, data, options) {

        var wrappedRequest = {
            data: data
        };

        var deferred = $q.defer();
        var resolved = false;

        socket.emit(url, wrappedRequest, function responseCallback(response) {
            if (response.success) {
                deferred.resolve(response.data);
                resolved = true;
            } else {
                deferred.reject(response);
                resolved = true;
            }
        });

        return deferred.promise;
    };

    return new WebSocketClient(socket);
})

;

Aviran Cohen
  • 5,581
  • 4
  • 48
  • 75