Sunday 11 February 2018

[Socket.IO, Express] Should app logic be in socket handlers or REST api?

Disclaimer: this is was posted on stackoverflow a few days ago. I received no answers so far probably because my question is a bit specific.I'm planning a non-trivial realtime chat platform. The app has several types of resources: Users, Groups, Channels, Messages. There are roughly 20 types of realtime events having to do with these resources: for instance, submitting a message, a user connecting or disconnecting, a user joining a group, a moderator kicking a user from a group, etc...Overall, I see two paths to organizing all this complexity.The first is to build a REST API to manage the resources. For instance, to send a message, POST to /api/v1/messages. Or, to kick a user from a group, POST to /api/v1/group/:group_id/kick/. Then, from within the Express route handler, call io.emit (made accessible through res.locals) with the updated data to notify all related clients. In this case, clients talk to the server through HTTP and the server notifies clients through socket.io.The other option is to not have a rest API at all, and handle all events through socket.IO. For instance, to send a message, emit a SEND_MESSAGE event. Or, to kick a user, emit a KICK_USER event. Then, from within the socket.io event handler, call io.emit with the updated data to notify all clients.Yet another option is to have certain actions handled by a REST API, others by socket.IO. For instance, to get all messages, GET api/v1/channel/:id/messages. But to post a message, emit SEND_MESSAGE to the socket.Which is the most suitable option? How do I determine which actions need to be sent through an API, and which need to be sent through socket.io? Is it better not to have a REST API for this type of application?

Submitted February 11, 2018 at 03:43PM by Tioo

No comments:

Post a Comment