Skip to content

augustos0204/room-stream-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

264 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ”Œ RoomStream - API

A robust and scalable WebSocket API built with NestJS and Socket.IO for creating and managing real-time chat rooms. Includes a complete web platform for managing rooms, applications, and more.

πŸ“‹ Table of Contents

✨ Features

🎯 Core Backend Features

  • Real-time room creation and management
  • Participant system with customizable names
  • Real-time messaging with persistent history
  • Multiple simultaneous rooms per user
  • Join/leave events with notifications
  • Comprehensive metrics system for monitoring
  • Application/API Key management for integrations

πŸ› οΈ Backend Architecture

  • Isolated WebSocket namespace (/ws/rooms)
  • Robust input validation on all endpoints
  • Automatic disconnection handling
  • Configurable CORS for different environments
  • Detailed logging and error handling
  • Modular NestJS architecture for scalability
  • Event-driven system with @nestjs/event-emitter
  • TypeScript implementation for type safety
  • Flexible storage (Redis or in-memory)

🌐 Web Platform

  • Complete SPA dashboard at /platform
  • Room management interface
  • Real-time chat interface
  • Application/API Key management
  • User profile (with Supabase auth)
  • GitHub integration for about page
  • PWA-ready with manifest files

πŸ” Authentication

  • Multiple auth methods: Supabase JWT, API Key, Application Key
  • Per-application API keys for integrations
  • Periodic token validation for Supabase

πŸ§ͺ Development Tools

  • Interactive Swagger docs at /docs/api
  • HTTP request files for endpoint validation
  • Health checks and metrics endpoints
  • Comprehensive logging for debugging

πŸš€ Technologies

Backend

Frontend (Platform)

  • EJS - Template engine
  • Tailwind CSS - Utility-first CSS (via CDN)
  • Custom CSS - For complex components and animations
  • Vanilla JavaScript - For interactivity

DevTools

πŸ“¦ Installation

Prerequisites

  • Node.js >= 18.x
  • pnpm >= 8.x (recommended) or npm/yarn
  • Redis (optional, for persistent storage)
  • Supabase project (optional, for authentication)

Clone Repository

git clone https://github.com/augustos0204/room-stream-api.git
cd room-stream-api

Install Dependencies

pnpm install
# or
npm install

βš™οΈ Configuration

1. Environment Variables

Copy the example file and configure the variables:

cp .env.example .env

Available Variables

# πŸš€ SERVER CONFIGURATION
PORT=3000                    # Server port

# 🌐 CORS CONFIGURATION
CORS_ORIGIN=*               # Allowed origin (* for development)

# πŸ”Œ WEBSOCKET CONFIGURATION
WEBSOCKET_NAMESPACE=/ws/rooms # Socket.IO namespace

# πŸ” SECURITY CONFIGURATION
API_KEY=your-secret-key     # Global API key (optional)
                            # Generate with: openssl rand -hex 32

# πŸ”‘ SUPABASE CONFIGURATION (optional)
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_ANON_KEY=your-anon-key

# πŸ’Ύ REDIS CONFIGURATION (optional)
REDIS_URL=redis://localhost:6379

# ⏱️ PRESENCE CONFIGURATION
ROOM_PARTICIPANT_TTL_SECONDS=120  # Participant presence TTL in seconds

# ⏱️ TOKEN VALIDATION
TOKEN_VALIDATION_INTERVAL=300000  # 5 minutes in ms

# πŸ™ GITHUB CONFIGURATION (optional)
GITHUB_CACHE_ENABLED=true   # Enable GitHub API cache

# πŸ“± APPLICATION SETTINGS
APP_NAME="RoomStream API"
APP_VERSION=1.0.0

2. Available Scripts

Development

pnpm run start:dev          # Server in watch mode
pnpm run start:debug        # Server with debug enabled

Production

pnpm run build             # Build for production
pnpm run start:prod        # Run compiled version

Code Quality

pnpm run lint              # Run ESLint
pnpm run format            # Format code with Prettier

🎯 Usage

Start Server

pnpm run start:dev

The server will be available at:

  • 🎯 REST API: http://localhost:3000
  • πŸ”Œ WebSocket: ws://localhost:3000/ws/rooms
  • 🌐 Web Platform: http://localhost:3000/platform
  • πŸ“š API Docs: http://localhost:3000/docs/api

πŸ“š API Endpoints

Rooms

Create Room

POST /rooms
Content-Type: application/json

{
  "name": "My Chat Room"
}

List All Rooms

GET /rooms

Get Specific Room

GET /rooms/:id

Delete Room

DELETE /rooms/:id

Get Room Messages

GET /rooms/:id/messages

Get Room Participants

GET /rooms/:id/participants

Applications (Requires Supabase Auth)

Create Application

POST /applications
Authorization: Bearer <supabase-jwt>
Content-Type: application/json

{
  "name": "My App",
  "description": "Optional description"
}

List User's Applications

GET /applications
Authorization: Bearer <supabase-jwt>

Get Specific Application

GET /applications/:id
Authorization: Bearer <supabase-jwt>

Update Application

PATCH /applications/:id
Authorization: Bearer <supabase-jwt>
Content-Type: application/json

{
  "name": "Updated Name",
  "isActive": true
}

Delete Application

DELETE /applications/:id
Authorization: Bearer <supabase-jwt>

Regenerate API Key

POST /applications/:id/regenerate-key
Authorization: Bearer <supabase-jwt>

Monitoring

Health Check

GET /health

System Metrics

GET /metrics

GitHub Profile (for about page)

GET /api/github/profile

πŸ” Authentication

Authentication Methods

The API supports multiple authentication methods:

Method Use Case Header/Auth
Application Key Server-to-server auth.applicationKey
Supabase JWT User authentication Authorization: Bearer
Global API Key Simple API access x-api-key header

Application Key Authentication

Create an application via the API or Platform to get an API key:

// WebSocket connection with application key
const socket = io('http://localhost:3000/ws/rooms', {
  auth: { applicationKey: 'app_your64hexcharacters...' }
});

Supabase Authentication

// WebSocket connection with Supabase token
const socket = io('http://localhost:3000/ws/rooms', {
  auth: { token: 'supabase-jwt-token' }
});

Global API Key Authentication

# REST API
curl -H "x-api-key: your-api-key" http://localhost:3000/rooms

# WebSocket
const socket = io('http://localhost:3000/ws/rooms', {
  auth: { apiKey: 'your-api-key' }
});

Note: If no authentication is configured, the API is open (useful for development).

πŸ”Œ WebSocket Events

Connection

const socket = io('http://localhost:3000/ws/rooms');

// With authentication
const socket = io('http://localhost:3000/ws/rooms', {
  auth: { 
    token: 'supabase-jwt',        // OR
    applicationKey: 'app_...',     // OR
    apiKey: 'global-api-key'
  }
});

Client β†’ Server Events

Join Room

socket.emit('joinRoom', {
  roomId: 'room-id',
  participantName: 'Your Name' // optional
});

Leave Room

socket.emit('leaveRoom', {
  roomId: 'room-id'
});

Send Message

socket.emit('sendMessage', {
  roomId: 'room-id',
  message: 'Your message here'
});

// Or use 'emit' for custom events
socket.emit('emit', {
  roomId: 'room-id',
  message: 'Custom event data',
  event: 'custom-event-name' // optional, defaults to 'message'
});

Get Room Info

socket.emit('getRoomInfo', {
  roomId: 'room-id'
});

Update Participant Name

socket.emit('updateParticipantName', {
  roomId: 'room-id',
  participantName: 'New Name'
});

Server β†’ Client Events

Joined Room

socket.on('joinedRoom', (data) => {
  console.log('Joined room:', data);
  // { roomId, roomName, participants, recentMessages }
});

User Joined

socket.on('userJoined', (data) => {
  console.log('User joined:', data);
  // { clientId, participantName, roomId, roomName, participantCount }
});

User Left

socket.on('userLeft', (data) => {
  console.log('User left:', data);
  // { clientId, participantName, roomId, roomName, participantCount }
});

New Message

socket.on('newMessage', (data) => {
  console.log('New message:', data);
  // { id, clientId, message, timestamp, roomId, event }
});

Room Info

socket.on('roomInfo', (data) => {
  console.log('Room info:', data);
  // { id, name, participantCount, participants, messageCount, createdAt }
});

Name Updated

socket.on('participantNameUpdated', (data) => {
  console.log('Name updated:', data);
  // { clientId, participantName, roomId }
});

Room Deleted

socket.on('roomDeleted', (data) => {
  console.log('Room deleted:', data);
  // { roomId, roomName, message }
});

Errors

socket.on('error', (error) => {
  console.error('Error:', error);
  // { message: 'Error description' }
});

🌐 Web Platform

The web platform at /platform provides a complete interface for:

Available Pages

Route Description
/platform Dashboard with overview
/platform/rooms Room listing and management
/platform/chat Real-time chat interface
/platform/applications API Key management
/platform/profile User profile (requires auth)
/platform/login Authentication page
/platform/about About page with GitHub integration
/platform/guide Documentation and usage guide
/platform/landing Landing page

Features

  • SPA Architecture: Smooth navigation without page reloads
  • Responsive Design: Works on desktop and mobile
  • Real-time Updates: Live room and message updates
  • Dark Mode Ready: CSS custom properties for theming
  • PWA Support: Manifest files for installation

πŸ“ Project Structure

src/
β”œβ”€β”€ πŸ“ application/           # Application/API Key management
β”‚   β”œβ”€β”€ application.controller.ts
β”‚   β”œβ”€β”€ application.module.ts
β”‚   β”œβ”€β”€ application.service.ts
β”‚   └── dto/
β”œβ”€β”€ πŸ“ common/                # Shared utilities
β”‚   β”œβ”€β”€ config/              # Configuration helpers
β”‚   β”œβ”€β”€ decorators/          # Custom decorators (@Public)
β”‚   β”œβ”€β”€ dto/                 # Shared DTOs
β”‚   β”œβ”€β”€ filters/             # Exception filters
β”‚   β”œβ”€β”€ guards/              # Auth guards
β”‚   β”œβ”€β”€ interceptors/        # Request interceptors
β”‚   β”œβ”€β”€ interfaces/          # Shared interfaces
β”‚   └── utils/               # Utility functions
β”œβ”€β”€ πŸ“ events/                # Event system
β”‚   β”œβ”€β”€ events.module.ts
β”‚   β”œβ”€β”€ events.service.ts
β”‚   └── metrics.events.ts
β”œβ”€β”€ πŸ“ github/                # GitHub integration
β”‚   β”œβ”€β”€ github.controller.ts
β”‚   β”œβ”€β”€ github.module.ts
β”‚   └── github.service.ts
β”œβ”€β”€ πŸ“ health/                # Health checks
β”‚   β”œβ”€β”€ health.controller.ts
β”‚   β”œβ”€β”€ health.module.ts
β”‚   └── health.service.ts
β”œβ”€β”€ πŸ“ memory/                # Storage abstraction
β”‚   β”œβ”€β”€ adapters/            # In-memory & Redis adapters
β”‚   β”œβ”€β”€ interfaces/
β”‚   β”œβ”€β”€ memory.module.ts
β”‚   └── memory.service.ts
β”œβ”€β”€ πŸ“ metrics/               # System metrics
β”‚   β”œβ”€β”€ metrics.controller.ts
β”‚   β”œβ”€β”€ metrics.module.ts
β”‚   └── metrics.service.ts
β”œβ”€β”€ πŸ“ platform/              # Web platform
β”‚   β”œβ”€β”€ pages/               # SPA pages (EJS)
β”‚   β”œβ”€β”€ components/          # Reusable components
β”‚   β”œβ”€β”€ public/              # Static assets & error pages
β”‚   β”‚   β”œβ”€β”€ styles/          # CSS files
β”‚   β”‚   β”œβ”€β”€ scripts/         # JavaScript files
β”‚   β”‚   └── media/           # Images, icons
β”‚   β”œβ”€β”€ platform.controller.ts
β”‚   β”œβ”€β”€ platform.module.ts
β”‚   └── pages.service.ts
β”œβ”€β”€ πŸ“ room/                  # Core - Chat rooms
β”‚   β”œβ”€β”€ dto/                 # Room DTOs
β”‚   β”œβ”€β”€ interfaces/          # Room interfaces
β”‚   β”œβ”€β”€ room.controller.ts   # REST endpoints
β”‚   β”œβ”€β”€ room.gateway.ts      # WebSocket gateway
β”‚   β”œβ”€β”€ room.module.ts
β”‚   └── room.service.ts      # Business logic
β”œβ”€β”€ πŸ“ supabase/              # Supabase integration
β”‚   β”œβ”€β”€ supabase.module.ts
β”‚   └── supabase.service.ts
β”œβ”€β”€ πŸ“ types/                 # Shared types
β”œβ”€β”€ app.controller.ts
β”œβ”€β”€ app.module.ts
β”œβ”€β”€ app.service.ts
└── main.ts                  # Entry point

πŸ§ͺ Testing

Run Tests

# Unit tests
pnpm run test

# Tests in watch mode
pnpm run test:watch

# E2E tests
pnpm run test:e2e

# Coverage
pnpm run test:cov

Manual API Testing

Use the Swagger UI at /docs/api or the provided .http files in the requests/ folder.

πŸ“Š Monitoring

Metrics System

The system automatically collects metrics:

  • Connections: Connected/disconnected users
  • Rooms: Created/deleted
  • Messages: Sent per room
  • Participants: Room join/leave events

Logs

Detailed logs for all operations:

[RoomGateway] Client connected on namespace /ws/rooms: abc123
[RoomService] Room created: room_1234567890_abc (My Room)
[RoomGateway] Client abc123 joined room: room_1234567890_abc

🀝 Contributing

  1. Fork the project
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add: AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Commit Standards

  • feat: New feature
  • fix: Bug fix
  • docs: Documentation
  • style: Formatting
  • refactor: Refactoring
  • test: Tests
  • chore: Maintenance

πŸš€ Deployment

Production Variables

NODE_ENV=production
PORT=3000
CORS_ORIGIN=https://your-domain.com
WEBSOCKET_NAMESPACE=/ws/rooms
API_KEY=your-secure-api-key-here
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_ANON_KEY=your-anon-key
REDIS_URL=redis://your-redis-host:6379

Docker

# Build
docker build -t roomstream-api .

# Run
docker run -p 3000:3000 --env-file .env roomstream-api

πŸ“ž Support

  • Documentation: Check this README and /docs/api
  • Issues: Use GitHub Issues
  • Contact: Start a discussion in the repository

Made with ❀️ using NestJS and Socket.IO

About

A platform for create and manage real time data channels.

Topics

Resources

License

Stars

Watchers

Forks

Contributors 2

  •  
  •