WebSocket Module
The WebSocket module is a comprehensive real-time communication system for the Comdeall platform that enables bidirectional communication between clients and the server. It provides secure messaging capabilities between therapists and parents/children, real-time online status tracking, and robust authentication mechanisms. The module is built on Socket.IO with JWT-based authentication, message persistence, and comprehensive error handling to support the therapy management workflow with instant communication.
Table of Contents
- Module Structure
- WebSocket Events
- Core Features
- Authentication & Security
- Message Management
- Online Status Tracking
- Real-time Communication
- Integration Points
- Technical Implementation
- Error Handling
- Best Practices
- Conclusion
Module Structure
The WebSocket module follows a gateway-based architecture with comprehensive security and messaging features:
@Module({
imports: [DBModule, JwtModule.register({})],
providers: [
SocketGateway,
SocketService,
WsAuthGuard,
CustomJwtService,
SocketHelper,
MessageSanitizer
],
exports: [SocketService],
})
export class SocketModule {}
Core Components:
-
Gateway Layer (
socket.gateway.ts): WebSocket event handling, connection management, and message routing -
Service Layer (
socket.service.ts): Business logic for messaging, online status management, and database operations -
Authentication Layer (
guards/ws-auth.guard.ts): JWT-based WebSocket authentication and user context management -
Helper Services (
helpers/socket.helper.ts): Utility functions for token extraction and socket operations -
Database Layer (
db/socket/): Message persistence, online status tracking, and data management
WebSocket Events
| Event | Direction | Description | Auth Required | Payload |
|---|---|---|---|---|
connection | Client → Server | Initial WebSocket connection | JWT Token | { auth: { token } } |
disconnect | Client → Server | WebSocket disconnection | No | None |
private-message | Client → Server | Send private message | Yes | MessageInputDto |
message | Client → Server | Broadcast message | Yes | object |
private-message | Server → Client | Receive private message | No | MessageInputDto |
exception | Server → Client | Error notification | No | { message, type, details } |
Event Flow:
- Connection: JWT authentication, user identification, online status update
- Private Messages: Direct messaging between therapists and parents/children
- Broadcast Messages: General message broadcasting capabilities
- Exception Handling: Comprehensive error communication to clients
Core Features
Real-time Messaging System
The module provides a comprehensive messaging system for therapy-related communications:
Message Types:
- Private Messages: Direct communication between therapists and parents/children
- Broadcast Messages: General announcements and group communications
- System Messages: Automated notifications and status updates
Message Features:
- Message Persistence: All messages saved to database for history and compliance
- Content Type Support: Text messages with extensible content type system
- UUID Generation: Automatic message ID generation for tracking and persistence
- Timestamp Management: Automatic creation timestamp with timezone support
Secure Authentication System
WebSocket connections implement JWT-based authentication with comprehensive security:
Authentication Flow:
- Token Extraction: JWT token extracted from WebSocket handshake
- Token Verification: Token validation using custom JWT service
- User Context: Hasura claims extraction for user identification and authorization
- Room Assignment: User-specific room assignment for targeted messaging
Security Features:
- Token Validation: Comprehensive JWT token verification with error handling
- User Context: Complete user information extraction from Hasura claims
- Automatic Disconnection: Invalid token leads to immediate connection termination
- Error Communication: Structured error messages sent to clients before disconnection
Online Status Management
Real-time user presence tracking supports therapy scheduling and communication:
Online Status Features:
- Connection Tracking: Automatic online status update on connection
- Disconnection Handling: Offline status update on disconnect
- Database Persistence: Online status stored in database for cross-session tracking
- Upsert Logic: Intelligent insert/update logic for status management
Status States:
ONLINE: User actively connected to WebSocketOFFLINE: User disconnected or session ended
Authentication & Security
JWT Authentication Guard
The WsAuthGuard implements comprehensive WebSocket authentication:
@Injectable()
export class WsAuthGuard implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
const client: Socket = context.switchToWs().getClient();
const token = this.socketHelper.getAuthTokenFromSocket(client);
const payload = await this.jwtService.verifyAccessToken(token);
client.data.user = {
email: payload.data['email'],
id: payload.data['https://hasura.io/jwt/claims'][HasuraClaims.USER_ID],
role: payload.data['https://hasura.io/jwt/claims'][HasuraClaims.DEFAULT_ROLE],
therapist_id: payload.data['https://hasura.io/jwt/claims'][HasuraClaims.THERAPIST_ID],
parent_id: payload.data['https://hasura.io/jwt/claims'][HasuraClaims.PARENT_ID],
};
return true;
}
}
Authentication Features:
- Token Extraction: Secure token retrieval from WebSocket handshake
- Hasura Integration: Compatible with Hasura GraphQL claims structure
- User Context: Complete user information attached to socket connection
- Role-based Access: User role and associated IDs for authorization
Connection Security
WebSocket connections implement multiple security layers:
Security Measures:
- Token Validation: JWT signature verification and expiration checking
- Connection Logging: Comprehensive connection attempt logging for security monitoring
- Error Handling: Structured error responses with appropriate error types
- Automatic Cleanup: Immediate disconnection for unauthorized access attempts
Privacy Protection:
- Room-based Messaging: Users only receive messages intended for them
- UUID Validation: Room names validated as UUIDs for security
- Message Sanitization: Input validation and sanitization for all message content
Message Management
Message Structure and Validation
Comprehensive message structure ensures data integrity and proper communication:
Message Schema:
export class MessageInputDto {
sender_type: CHAT_MEDIUM; // CHILD | THERAPIST
recipient_type: CHAT_MEDIUM; // CHILD | THERAPIST
recipient_id: string; // UUID of recipient
child_id: string | null; // Child ID for context
text: string; // Message content
content_type: string; // MIME type
created_at?: Date | string; // Timestamp
}
Validation Features:
- Enum Validation: Sender and recipient types validated against allowed values
- UUID Validation: All IDs validated as proper UUIDs
- Content Validation: Message text and content type validation
- Timestamp Handling: Automatic timestamp generation with custom override support
Message Persistence and Database Integration
All messages are persisted to the database for compliance and history:
Database Operations:
- Message Saving: Individual and bulk message persistence
- Message History: Retrieval of recent messages for conversation continuity
- Read Status: Message read status tracking and management
- Bulk Operations: Efficient bulk message processing for performance
Message Storage Features:
- Comprehensive Logging: All messages logged with full metadata
- Relationship Tracking: Child-therapist-parent relationship context preservation
- Content Type Support: Extensible content type system for future media support
- Audit Trail: Complete message audit trail for compliance requirements
Online Status Tracking
Real-time Presence Management
The module tracks user presence for therapy scheduling and communication coordination:
Presence Tracking:
- Connection Events: Automatic online status on successful authentication
- Disconnection Events: Automatic offline status on client disconnect
- Status Persistence: Online status stored in database for cross-session tracking
- Bulk Operations: Efficient status management for multiple users
Status Management Methods:
// Individual status operations
await this.socketDBService.insertOnlineStatus(userId, ONLINE_STATUS.ONLINE);
await this.socketDBService.updateOnlineStatus(userId, ONLINE_STATUS.OFFLINE);
// Bulk operations
await this.socketDBService.resetAllOnlineStatus();
await this.socketDBService.getAllOnlineUsers();
Connection Lifecycle Management
Comprehensive connection lifecycle ensures accurate presence tracking:
Connection Flow:
- Authentication: JWT token verification and user identification
- Room Assignment: User assigned to personal room using user ID
- Status Update: Online status updated in database
- Ready State: Connection ready for message exchange
Disconnection Flow:
- Room Analysis: User ID extracted from socket rooms
- Status Update: Offline status updated in database
- Cleanup: Connection resources cleaned up
- Logging: Disconnection logged for monitoring
Real-time Communication
Private Messaging System
Direct messaging between therapists and parents/children with room-based delivery:
Private Message Flow:
- Authentication: User authentication via WsAuthGuard
- Message Validation: Input validation using ValidationPipe
- Room Delivery: Message sent to both sender and recipient rooms
- Database Persistence: Message saved to database with full metadata
- Real-time Delivery: Instant message delivery to connected clients
Message Delivery:
// Room-based message delivery
this.io.to(payload.recipient_id).to(sender_id).emit('private-message', payload);
// Database persistence
await this.saveMessagesInDB([msgData]);
Broadcast Messaging
General message broadcasting capabilities for announcements and group communications:
Broadcast Features:
- Authenticated Broadcasting: Requires user authentication for broadcast privileges
- Flexible Payload: Support for various message types and content
- Exclusion Logic: Broadcaster excluded from receiving their own broadcast
- Real-time Delivery: Instant delivery to all connected clients except sender
Integration Points
Database Integration
Comprehensive database integration for message persistence and status tracking:
Database Operations:
- Message Storage: Messages saved with full metadata and relationship context
- Online Status: User presence tracked across sessions and devices
- Message History: Complete conversation history with pagination support
- Bulk Operations: Efficient bulk processing for high-volume scenarios
Repository Pattern:
- Abstraction Layer: Clean separation between business logic and data access
- Transaction Support: Database transactions for data consistency
- Error Handling: Comprehensive error handling for database operations
- Performance Optimization: Optimized queries for real-time performance requirements
JWT Service Integration
Seamless integration with the application's JWT authentication system:
JWT Integration:
- Token Verification: Reuse of existing JWT verification logic
- Hasura Claims: Compatible with Hasura GraphQL authorization system
- User Context: Complete user information extraction from token claims
- Error Handling: Consistent error handling with REST API authentication
Technical Implementation
Socket.IO Configuration
The module uses Socket.IO for WebSocket communication with comprehensive configuration:
Gateway Configuration:
@WebSocketGateway()
@UseFilters(AllWsExceptionFilter)
@UsePipes(new ValidationPipe({
transform: true,
exceptionFactory: (errors) => new WsException({
message: 'Validation failed',
type: 'VALIDATION_ERROR',
details: errors
})
}))
Features:
- Global Exception Handling: Comprehensive error handling for all WebSocket operations
- Input Validation: Automatic validation using class-validator decorators
- Error Transformation: Structured error responses with detailed validation information
- Transform Support: Automatic payload transformation and type conversion
Room Management Strategy
User-based room assignment ensures secure and targeted message delivery:
Room Strategy:
- User Rooms: Each user assigned to a room using their user ID
- UUID Validation: Room names validated as UUIDs for security
- Message Targeting: Messages delivered to specific user rooms
- Presence Tracking: Room membership used for online status determination
Error Handling Architecture
Comprehensive error handling ensures robust WebSocket communication:
Error Categories:
- Authentication Errors: Invalid tokens, expired sessions, unauthorized access
- Validation Errors: Invalid message format, missing required fields
- System Errors: Database connectivity, server errors, unexpected exceptions
- Communication Errors: Message delivery failures, connection issues
Error Response Format:
client.emit('exception', {
message: errorMessage,
type: errorType,
details: errorDetails,
traceId: errorTraceId,
chatId: errorChatId
});
Error Handling
The module implements comprehensive error handling for reliable WebSocket communication:
Error Types:
- Unauthorized Access: Invalid or missing JWT tokens with immediate disconnection
- Validation Errors: Message format validation with detailed field-level errors
- System Errors: Database and server errors with appropriate client notification
- Network Errors: Connection issues with retry guidance and status information
Error Management Features:
- Structured Responses: Consistent error format across all error types
- Client Notification: Immediate error notification to clients with actionable information
- Logging Integration: Comprehensive error logging for debugging and monitoring
- Graceful Degradation: System continues operation despite individual connection failures
Best Practices
Security Considerations
WebSocket security best practices ensure safe real-time communication:
Security Practices:
- Token Validation: Always validate JWT tokens before processing any WebSocket events
- Room Security: Use UUIDs for room names to prevent unauthorized access
- Input Sanitization: Validate and sanitize all incoming message content
- Connection Limits: Implement connection limits to prevent resource exhaustion
Performance Optimization
Real-time communication optimization ensures scalable performance:
Performance Practices:
- Connection Pooling: Efficient database connection management
- Bulk Operations: Use bulk database operations for high-volume scenarios
- Room Targeting: Precise message targeting to minimize bandwidth usage
- Status Caching: Cache online status for frequently accessed user presence data
Messages Management
Effective message management ensures reliable communication:
Message Practices:
- Persistence Priority: Always persist messages before real-time delivery
- Content Validation: Validate message content and format before processing
- Metadata Tracking: Include comprehensive metadata for audit and compliance
- Error Recovery: Implement message retry mechanisms for delivery failures
Conclusion
The WebSocket module provides a comprehensive real-time communication foundation for the Comdeall platform, enabling secure and reliable messaging between therapists, parents, and children. Key strengths include:
Real-time Communication:
- Bidirectional Messaging: Instant communication with message persistence and delivery confirmation
- Online Presence: Real-time user status tracking for therapy scheduling and coordination
- Secure Authentication: JWT-based authentication with comprehensive security measures
- Message Management: Complete message lifecycle with validation, persistence, and delivery
Production-Ready Features:
- Error Handling: Comprehensive error management with structured client notification
- Performance Optimization: Efficient room-based messaging with database optimization
- Security Implementation: Multi-layered security with token validation and input sanitization
- Integration Architecture: Seamless integration with existing JWT and database systems
Scalable Design:
- Room Management: Efficient user-based room assignment for targeted messaging
- Database Integration: Robust message persistence with bulk operation support
- Status Tracking: Comprehensive online status management across sessions
- Monitoring Support: Complete logging and error tracking for operational excellence
The module's architecture supports the critical real-time communication needs of the therapy management platform, ensuring reliable, secure, and efficient messaging capabilities that enhance the therapeutic relationship between all stakeholders in the child development process.