1.0.3 โ€ข Published 11 months ago

@dyniqo/ts-websocket v1.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

WebSocket Management Library

A robust and flexible TypeScript library for managing WebSocket connections alongside an HTTP server. This library provides seamless integration into Node.js applications with built-in support for dependency injection, modular design, and extensibility.


๐Ÿ“œ Features

  • ๐ŸŒ Unified HTTP and WebSocket Management: Simplifies handling both HTTP and WebSocket protocols.
  • ๐Ÿงฉ Dependency Injection: Powered by inversify for modular and testable architecture.
  • ๐Ÿ› ๏ธ Highly Extensible: Offers interfaces and hooks for custom implementations (e.g., authentication, logging).
  • ๐Ÿ”Œ Middleware Support: Easily add HTTP and WebSocket middleware.
  • ๐Ÿ“ TypeScript First: Fully typed APIs for safer and more productive development.

๐Ÿ“ฆ Installation

Install the package using npm or yarn:

npm install @dyniqo/ts-websocket
yarn add @dyniqo/ts-websocket

โš™๏ธ Usage

๐Ÿ› ๏ธ Basic Setup

The WebSocketManager class is the core component of the library. Here is an example of its usage:

import { WebSocketManager } from '@dyniqo/ts-websocket';

// Configuration options
const options = {
  port: 3000,
  enableLogging: true,
};

// Initialize WebSocketManager
const wsManager = new WebSocketManager(options);

// Start the server
wsManager.start().then(() => {
  console.log('WebSocket server is running!');
});

๐Ÿ“š API Documentation

๐Ÿ–ฅ๏ธ WebSocketManager

๐Ÿ“– Methods:

  • constructor(options: IWebSocketManagerOptions): Initialize the WebSocket manager with configuration.
  • start(): Promise<void>: Start the HTTP and WebSocket servers.
  • stop(): Promise<void>: Stop the servers gracefully.
  • onConnection(handler: (socket: WebSocket) => void): void: Register a handler for new WebSocket connections.

โš™๏ธ Configuration Options (IWebSocketManagerOptions)

The IWebSocketManagerOptions interface provides configuration properties to customize the WebSocketManager. Below are the available options:

PropertyTypeDefaultDescription
portnumber8080The port number for the WebSocket server.
secretKeystring'default_secret'Secret key used for token generation and authentication.
tokenExpirystring'1h'The expiration duration for generated tokens (e.g., '1h', '2d').
enableLoggingbooleantrueFlag to enable or disable logging.
wsOptionsServerOptionsundefinedAdditional options for the WebSocket server.
setupRoutes(app: Application) => voidundefinedCallback for setting up application routes in the Express application.
beforeSend(message: IMessage<any>) => voidundefinedHook executed before a message is broadcasted.
afterSend(message: IMessage<any>) => voidundefinedHook executed after a message is broadcasted.
onMessage(message: IMessage<any>) => voidundefinedCustom handler for processing incoming WebSocket messages.

๐Ÿง‘โ€๐Ÿ’ป Usage Example

import { WebSocketManager } from '@dyniqo/ts-websocket';

const wsManager = new WebSocketManager({
  port: 8080,
  secretKey: 'anySecretKey',
  tokenExpiry: '2h',
  enableLogging: true,
  beforeSend: (message) => {
    console.log('Before sending message:', message);
  },
  afterSend: (message) => {
    console.log('After sending message:', message);
  },
  onMessage: (message) => {
    console.log('Received message:', message);
  },
  setupRoutes: (app) => {
    app.get('/status', (req, res) => {
      res.send('Server is running!');
    });
  },
});

wsManager.start();

๐Ÿš€ Advanced Usage

๐Ÿ”Œ Middleware Integration

Add middleware for HTTP requests or WebSocket connections:

wsManager.use((req, res, next) => {
  console.log(`HTTP Request: ${req.method} ${req.url}`);
  next();
});

๐ŸŒ WebSocket Event Handlers

Define handlers for WebSocket events:

wsManager.onConnection((socket) => {
  console.log('New connection established.');

  socket.on('message', (msg) => {
    console.log(`Received message: ${msg}`);
    socket.send('Hello, Client!');
  });

  socket.on('close', () => {
    console.log('Connection closed.');
  });

  socket.on('error', (err) => {
    console.error(`Error: ${err.message}`);
  });
});

๐Ÿ”„ Lifecycle Hooks

The library provides lifecycle hooks to customize the behavior at different stages:

๐Ÿ–ฅ๏ธ Server Lifecycle

wsManager.onStart(() => {
  console.log('Server is starting...');
});

wsManager.onStop(() => {
  console.log('Server is shutting down...');
});

โœ‰๏ธ Message Lifecycle

  • beforeSend: Modify or validate messages before they are sent.
wsManager.beforeSend((message, socket) => {
  console.log('Preparing to send message:', message);
  // Modify the message if needed
  return message;
});
  • afterSend: Perform actions after a message is sent.
wsManager.afterSend((message, socket) => {
  console.log('Message sent:', message);
  // Additional post-send logic here
});

๐Ÿงช Testing

Run tests using:

npm run test

๐Ÿ“ฌ Contact Us

We'd love to hear from you! If you have questions, suggestions, or need support, here are the ways to reach us:

๐Ÿ“ง Email: dyniqo@gmail.com
๐Ÿ› GitHub Issues: Open an Issue

We look forward to hearing from you!