Search This Blog

Easy pub/sub channels/messaging with ES6 and Websockets!

I didn't want to pull in a library to get "message types" or "channels" for my messages between the browser and NodeJS. Out of playing around, I think I discovered something beautiful. It is easy to understand and extend. Sure it doesn't have caching or anything fancy, and is definitely not for enterprise software, but if you need only something simple for pub/sub channels, I think this is perfect! So great that I just had to share it.

Someone requested I do a little explanation, so I'm copying what I wrote on Reddit to over here. I initially thought it would be better to let readers try and figure out what is happening on their own.

Basically a message comes in to the server as this object:

{ type, result }

Then I find the function name that matches the "type" property.

I (was) am using shorthand for objects (valid ES6).

As of about 5 minutes ago I thought of a more robust way to do this, incase you are sending bad messages: