Skip to content

Dandelight/node-pubsub

Repository files navigation

Node.js WebSocket PubSub Server

A real-time messaging server built with Node.js, WebSocket, and Redis PubSub.

Prerequisites

  • Node.js 18 or higher
  • pnpm
  • Redis
  • MongoDB

Installation

pnpm install

Configuration

Create a .env file in the root directory with the following variables:

MONGODB_URI=mongodb://localhost:27017/pubsub
REDIS_URL=redis://localhost:6379
PORT=8080

WebSocket Connection

Connect to the WebSocket server with a userId parameter:

const ws = new WebSocket('ws://localhost:8080?userId=user123');

Message Protocol

All messages follow this JSON format:

interface WebSocketMessage {
  action: string;
  [key: string]: any;
}

Available Actions

1. Sync Messages

Request:

{
  "action": "syncMessages",
  "clientMaxMessageId": "lastMessageId"
}

Response:

{
  "action": "syncMessagesResponse",
  "messages": [
    {
      "id": "messageId",
      "content": "message content",
      "timestamp": "2024-01-01T00:00:00Z"
    }
  ]
}

2. Join Group

Request:

{
  "action": "joinGroup",
  "groupId": "group123",
  "role": "member"
}

Response:

{
  "action": "joinGroupResponse",
  "success": true
}

3. Send Group Message

Request:

{
  "action": "sendGroupMessage",
  "groupId": "group123",
  "content": "Hello, group!",
  "isInRole": true
}

Error Handling

When an error occurs, the server responds with:

{
  "action": "error",
  "error": "Error message description"
}

Development

Start the development server:

pnpm dev

Docker Support

Run with Docker Compose:

docker-compose up -d

This will start:

  • The WebSocket server
  • Redis
  • MongoDB

License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published