REST API chat - endpoint for receiving real-time messages

I have a REST API server running express mongodb. There are multiple endpoints with different resources. One of them is the chat API. I already have a few basic endpoints, for example:

  • POST http://api.example.com/v1/chat

    - to create a chat
  • POST http://api.example.com/v1/chat/:id/message

    - send a message to an existing chat
  • GET http://api.example.com/v1/chat/:id/messages

    - to receive messages in the specified chat

But I need to provide API users with the ability to efficiently receive new messages in real time without reloading the page.

Now that you can see that it is possible to simply poll the endpoint GET

from the client, but it seems ineffective. For example, a client can have a user interface that will show new messages in the header (some kind of notifications).

I was thinking about websites. Is it possible, for example, to provide an endpoint, for example /chat/:id/subscribe

, that will use a proxy socket server and connect to it on the client?

Are there any good examples of this kind of API design where I can get some inspiration or maybe you can give me some advice? Thank!

+3


source to share


1 answer


socket.io is the package you are looking for.

The namespace section in the documentation is a good solution, since the namespace can be protected by authorization. It is a pool of connected sockets.

This is how I would do it:

Create a chat document between two users using this route:

POST http://api.example.com/v1/chat

      

Create a namespace with socket.io when the user sends a message to another connected user and stores it in your custom document in your database. This route will create a namespace and / or emit a message:



POST http://api.example.com/v1/chat/:id/message

      

On the client, you need to use socket.io again to listen for messages in the namespace.

UPDATE FOR SPEED:

Here is a good answer to a stackoverflow question about implementing a scalable chat server: Strategy for deploying a scalable chat server

As you can see in this post, mongodb may not be the best solution for storing your messages.

+1


source







All Articles