npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@dyniqo/ts-websocket

v1.0.3

Published

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.

Downloads

222

Readme

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:

| Property | Type | Default | Description | |------------------|------------------------------------|--------------------|--------------------------------------------------------------------------------------------------| | port | number | 8080 | The port number for the WebSocket server. | | secretKey | string | 'default_secret' | Secret key used for token generation and authentication. | | tokenExpiry | string | '1h' | The expiration duration for generated tokens (e.g., '1h', '2d'). | | enableLogging | boolean | true | Flag to enable or disable logging. | | wsOptions | ServerOptions | undefined | Additional options for the WebSocket server. | | setupRoutes | (app: Application) => void | undefined | Callback for setting up application routes in the Express application. | | beforeSend | (message: IMessage<any>) => void| undefined | Hook executed before a message is broadcasted. | | afterSend | (message: IMessage<any>) => void| undefined | Hook executed after a message is broadcasted. | | onMessage | (message: IMessage<any>) => void| undefined | Custom 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: [email protected]
🐛 GitHub Issues: Open an Issue

We look forward to hearing from you!