4

I have a REST API server powered by express+mongodb. There are a couple of endpoints with different resources. One of them is chat API. I already have several basic endpoints like:

  • POST http://api.example.com/v1/chat - to create chat
  • POST http://api.example.com/v1/chat/:id/message - to send message to existing chat
  • GET http://api.example.com/v1/chat/:id/messages - to get messages in the the specified chat

But I need to provide a way for API consumers to efficiently get new messages in real-time without reloading the page.

For now as you see it's possible just to poll GET endpoint from client but it seems not performant. For example client can have UI which will show new messages count in header (some kind of notifications).

I was thinking about websockets. Is it possible for example to provide endpoint like /chat/:id/subscribe which will proxy sockets' server and connect to it on client?

Is there some good examples of such API design where I can get inspiration from or maybe you can give me piece of advice? Thanks!

Kosmetika
  • 20,774
  • 37
  • 108
  • 172

1 Answers1

2

socket.io is the package you are looking for.

The namespace section in it's documentation is a good solution because namespaces can be authorization protected. It represents a pool of connected sockets.

Here is how I would do it :

Create a document for the chat between the two users with this route :

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

Create a namespace with socket.io when a user sends a message to another connected user and store it into your user's document in your database. This route would create a namespace and/or emit the message :

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

In the client, you have to use socket.io again to listen to the messages in the namespace.

UPDATE FOR SCALABILITY :

Here is a good stackoverflow answered question about implementing a scalable chat server : Strategy to implement a scalable chat server

As you can see in this post, mongodb might not be the best solution to store your messages.

Community
  • 1
  • 1
AlexB
  • 3,518
  • 4
  • 29
  • 46