Handle message before event ws nodejs

166 Views Asked by At

I'm using ws version 7.4.0 and I would want to display a console log or perfom operations between the moment where the client is sending a message to the server and before the server fire the on event message.

To represent it:

webserver.on('example', function callback(msg){console.log(msg);}); //act before the call of callback

client------server---[here]---callback

The only way I see right now would be to use a "root" function before the callback of all my events like this:

function callback(msg){console.log(msg);}
webserver.on('example', function root(msg) {console.log('example msg'); callback(msg);});

I don't know if this is a real and/or good solution I really wish to write a clean and organized application. If someone could give me some advise or a real solution? Thank you.

1

There are 1 best solutions below

2
On BEST ANSWER

You could make a wrapper for all of your callbacks like so:

function makeCallback(fn) {
  return function(msg) {
    if (!environment.prod) console.log(msg);
    fn(msg)
  };
}

var myCallback = makeCallback(function (msg) {
  // something
});

webserver.on('example', myCallback);

Or I think the better solution is to stream the requets into your stdout although I don't know the implications of using this method.

And I want to address the naming of your websocket server. Even though a web socket server is technically a web server, it only responds to the websocket protocol and naming it webserver could be misleading, I would recommend using the naming like in their documents wss.