/* eslint-disable @typescript-eslint/no-explicit-any */ import { SocketHandler, SocketRegistry, EnhancedSocketServer, AbstractSocket, SocketMessage } from "../src/infra/socket"; import { IO } from "../src/infra/common"; import { SocketHandlerOptions } from "../src/infra/socket/socket.handler"; // Example 1: Basic Socket Handler with IO class ChatIO implements IO { from(source: T): ChatInput { const { socket, data } = source as { socket: AbstractSocket; data: any }; return { message: data.message, userId: data.userId, timestamp: new Date(), socketId: (socket as any).id || 'unknown' }; } to(result: any, target: T): void { const socket = target as AbstractSocket; const response: SocketMessage = { type: 'chat_response', payload: { success: true, message: result.message, timestamp: result.timestamp } }; socket.send(JSON.stringify(response)); } } interface ChatInput { message: string; userId: string; timestamp: Date; socketId: string; } interface ChatOutput { message: string; timestamp: Date; success: boolean; } // Example 2: Authentication Middleware for Sockets const authMiddleware = async (socket: AbstractSocket, data: any, eventName: string): Promise => { const token = data.token || (socket as any).token; if (!token) { throw new Error('Authentication required'); } // Validate token logic here console.log(`Authenticated socket for event: ${eventName}`); }; // Example 3: Rate Limiting Middleware const rateLimitMiddleware = async (socket: AbstractSocket, data: any, eventName: string): Promise => { const socketId = (socket as any).id; // Implement rate limiting logic here console.log(`Rate limiting check for socket: ${socketId}, event: ${eventName}`); }; // Example 4: Logging Middleware const loggingMiddleware = async (socket: AbstractSocket, data: any, eventName: string, result?: any): Promise => { console.log(`Socket event: ${eventName}`, { socketId: (socket as any).id, data, result, timestamp: new Date() }); }; // Example 5: Chat Handler const chatHandler = async (input: ChatInput, socket: AbstractSocket, eventName: string): Promise => { console.log(`Processing chat message from ${input.userId}: ${input.message}`); // Process the chat message return { message: `Echo: ${input.message}`, timestamp: new Date(), success: true }; }; // Example 6: User Join Handler const userJoinHandler = async (data: any, socket: AbstractSocket, eventName: string): Promise => { const userId = data.userId; console.log(`User ${userId} joined the chat`); // Broadcast to all other users return { type: 'user_joined', payload: { userId, timestamp: new Date() } }; }; // Example 7: Setting up the Socket Registry export function setupSocketRegistry(): SocketRegistry { const registry = new SocketRegistry(); // Chat handler with authentication and logging registry.create( 'chat_message', chatHandler, { middlewares: { pre: [authMiddleware, rateLimitMiddleware], post: [loggingMiddleware] }, auth: { required: true, roles: ['user'] }, rateLimit: { maxRequests: 10, windowMs: 60000 } }, new ChatIO() ); // User join handler registry.create( 'user_join', userJoinHandler, { middlewares: { pre: [authMiddleware], post: [loggingMiddleware] }, auth: { required: true } } ); // Multiple event handler registry.create( ['ping', 'pong'], async (data: any, socket: AbstractSocket, eventName: string) => { const response = eventName === 'ping' ? 'pong' : 'ping'; socket.send(JSON.stringify({ type: response, payload: { timestamp: new Date() } })); } ); return registry; } // Example 8: Using EnhancedSocketServer with Fluent API export function createEnhancedSocketServer() { // Mock socket server implementation const mockServer = { onConnection: (callback: (client: AbstractSocket, req: any) => void) => { // Mock connection handling }, send: (client: AbstractSocket, message: string) => { console.log('Sending message:', message); }, isClientConnected: (client: AbstractSocket) => true, ping: (client: AbstractSocket) => { console.log('Pinging client'); }, close: () => { console.log('Closing server'); } }; const registry = setupSocketRegistry(); // Fluent API usage const server = new EnhancedSocketServer(mockServer, { port: 3000, heartbeatInterval: 30000, onConnection: (clientId: string) => { console.log(`Client connected: ${clientId}`); }, onDisconnection: (clientId: string) => { console.log(`Client disconnected: ${clientId}`); }, onError: (clientId: string, error: Error) => { console.error(`Client error ${clientId}:`, error); }, onMessage: (clientId: string, message: SocketMessage) => { console.log(`Message from ${clientId}:`, message); } }) .use(registry) .configure({ heartbeatInterval: 25000, rateLimit: 50 }) .start(); return server; } // Example 9: Advanced IO for Real-time Notifications class NotificationIO implements IO { from(source: T): NotificationInput { const { socket, data } = source as { socket: AbstractSocket; data: any }; return { type: data.type, message: data.message, targetUsers: data.targetUsers || [], priority: data.priority || 'normal', metadata: data.metadata || {} }; } to(result: any, target: T): void { const socket = target as AbstractSocket; // Send to specific users or broadcast if (result.targetUsers && result.targetUsers.length > 0) { // Send to specific users (would need user-to-socket mapping) result.targetUsers.forEach((userId: string) => { // Implementation would depend on how you map users to sockets console.log(`Sending notification to user ${userId}:`, result); }); } else { // Broadcast to all const response: SocketMessage = { type: 'notification', payload: result }; socket.send(JSON.stringify(response)); } } } interface NotificationInput { type: string; message: string; targetUsers?: string[]; priority: 'low' | 'normal' | 'high'; metadata: Record; } interface NotificationOutput { id: string; type: string; message: string; timestamp: Date; targetUsers?: string[]; priority: string; } // Example 10: Complete Usage Example with Fluent API export function completeExample() { const registry = new SocketRegistry(); // Add notification handler registry.create( 'send_notification', async (input: NotificationInput, socket: AbstractSocket) => { return { id: `notif_${Date.now()}`, type: input.type, message: input.message, timestamp: new Date(), targetUsers: input.targetUsers, priority: input.priority }; }, { middlewares: { pre: [authMiddleware], post: [loggingMiddleware] }, auth: { required: true, roles: ['admin'] } }, new NotificationIO() ); // Create server with fluent API const server = new EnhancedSocketServer(mockServer, { port: 3000, heartbeatInterval: 30000 }) .use(registry) .configure({ rateLimit: 100 }) .start(); console.log('Enhanced socket server setup complete!'); console.log(`Total handlers registered: ${registry.getHandlerCount()}`); console.log(`Events registered: ${registry.getEventNames().join(', ')}`); return { registry, server }; } // Example 11: Handler Options Configuration const handlerOptions: SocketHandlerOptions = { middlewares: { pre: [authMiddleware, rateLimitMiddleware], post: [loggingMiddleware] }, auth: { required: true, roles: ['user', 'admin'] }, rateLimit: { maxRequests: 20, windowMs: 60000 }, validation: { schema: { type: 'object', properties: { message: { type: 'string', minLength: 1 }, userId: { type: 'string' } }, required: ['message', 'userId'] } } }; // Example 12: Creating handlers with different configurations export function createHandlersWithOptions() { const registry = new SocketRegistry(); // Public handler (no auth required) registry.create('public_message', publicHandler, { rateLimit: { maxRequests: 5, windowMs: 60000 } }); // Admin-only handler registry.create('admin_action', adminHandler, { auth: { required: true, roles: ['admin'] }, middlewares: { pre: [authMiddleware], post: [loggingMiddleware] } }); // User handler with validation registry.create('user_update', userUpdateHandler, { auth: { required: true, roles: ['user'] }, validation: { schema: { type: 'object', properties: { name: { type: 'string' }, email: { type: 'string', format: 'email' } } } } }); return registry; } // Mock handlers for examples const publicHandler = async (data: any, socket: AbstractSocket) => { console.log('Public message received:', data); }; const adminHandler = async (data: any, socket: AbstractSocket) => { console.log('Admin action executed:', data); }; const userUpdateHandler = async (data: any, socket: AbstractSocket) => { console.log('User updated:', data); };