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 🙏

© 2026 – Pkg Stats / Ryan Hefner

clean-nodejs-sockets

v1.5.0

Published

Modular WebSocket service with abstracted persistence and optional authentication

Downloads

43

Readme

🚀 Clean Node.js Sockets

Un SDK modular para comunicación en tiempo real con Socket.IO, diseñado para proyectos Node.js + Express. Abstrae la configuración base y proporciona una arquitectura extensible con handlers preconstruidos para chat y notificaciones.

🎯 Características

  • Configuración automática de Socket.IO con CORS
  • Handlers preconstruidos para chat y notificaciones
  • Arquitectura modular con gestión de handlers y repositorios
  • Integración opcional de persistencia mediante Patrón Repository
  • No acoplamiento a base de datos específica (Null Object Pattern)
  • TypeScript con tipos completos y interfaces claras
  • Listo para integrarse en cualquier backend con Express

🧩 Arquitectura

app-server.js ──┐
                ▼
        ┌───────────────┐
        │  SocketCore   │ ← Fachada principal
        └───────────────┘
                │
        ┌───────┼───────┐
        ▼       ▼       ▼
EventHandler  Repository  Handlers
Manager      Manager     Base
                        │
                ┌───────┼───────┐
                ▼       ▼       ▼
            Chat    Notification  [Custom]
            Handler   Handler     Handlers

📦 Instalación

npm install clean-nodejs-sockets

🚀 Uso Básico

const express = require('express');
const http = require('http');
const { initSocketCore } = require('clean-nodejs-sockets');

const app = express();
const server = http.createServer(app);

// Inicialización simple
const io = initSocketCore(server, {
  cors: {
    origin: "http://localhost:3000",
    credentials: true
  }
});

app.get('/', (req, res) => {
  res.send('Servidor funcionando!');
});

server.listen(3000, () => {
  console.log('Servidor corriendo en puerto 3000');
});

📋 Eventos Disponibles

Chat Handler

  • message:send → Envía mensaje a sala
  • user:join → Usuario se une a sala
  • user:leave → Usuario abandona sala
  • user:typing → Usuario está escribiendo

Notification Handler

  • notification:send → Envía notificación a usuario específico
  • notification:bulk_send → Envía notificaciones masivas a múltiples usuarios
  • notification:mark_read → Marca notificación como leída

🔧 Configuración Avanzada

const io = initSocketCore(server, {
  repositories: {
    messageRepository: new MongoMessageRepository(),
    notificationRepository: new MongoNotificationRepository(),
  },
  handlers: [new ChatHandler(), new NotificationHandler()], // o instancias
  cors: {
    origin: "http://localhost:3000",
    credentials: true
  }
});

🏗️ Extensibilidad

Crear Handler Personalizado

const { BaseHandler, SocketCore } = require('clean-nodejs-sockets');

class GameHandler extends BaseHandler {
  register(socket, repositories) {
    socket.on('game:join', (data) => {
      // Lógica del handler
      socket.join(`game_${data.gameId}`);
      socket.to(`game_${data.gameId}`).emit('player:joined', data);
    });

    socket.on('game:move', (data) => {
      socket.to(`game_${data.gameId}`).emit('game:move_made', data);
    });
  }
}

// Usar handler personalizado
const socketCore = new SocketCore({
  handlers: [new GameHandler()]
});
const io = socketCore.start(server);

Implementar Repositorio Personalizado

const { IMessageRepository, INotificationRepository } = require('clean-nodejs-sockets');

class MongoMessageRepository extends IMessageRepository {
  async save(message) {
    // Implementación con MongoDB
    return await MessageModel.create(message);
  }

  async findByRoom(roomId) {
    return await MessageModel.find({ roomId });
  }
}

class MongoNotificationRepository extends INotificationRepository {
  async save(notification) {
    // Implementación con MongoDB
    return await NotificationModel.create(notification);
  }

  async findByUser(userId) {
    return await NotificationModel.find({ targetUserId: userId });
  }
}

🧠 Patrones de Diseño Utilizados

| Patrón | Aplicación | |--------|------------| | Facade | SocketCore simplifica la inicialización | | Strategy | EventHandlerManager gestiona handlers dinámicamente | | Repository | Abstracción de persistencia con interfaces | | Template Method | BaseHandler define flujo base para handlers | | Dependency Injection | Inyección de repositorios y handlers | | Null Object | Repositorios nulos cuando no se especifican | | Factory | Creación automática de handlers por defecto |

📁 Estructura del Proyecto

src/
├── core/
│   ├── EventHandlerManager.ts # Gestión de handlers
│   ├── RepositoryManager.ts   # Gestión de repositorios
│   └── SocketCore.ts          # Fachada principal
├── handlers/
│   ├── ChatHandler.ts         # Handler de chat
│   └── NotificationHandler.ts # Handler de notificaciones
├── interfaces/
│   ├── Handlers.ts            # Interfaces de handlers
│   └── Repositories.ts        # Interfaces de repositorios
└── types/
    └── core.types.ts          # Tipos TypeScript

🤝 Contribuir

  1. Fork el proyecto
  2. Crea tu rama de feature (git checkout -b feature/AmazingFeature)
  3. Commit tus cambios (git commit -m 'Add some AmazingFeature')
  4. Push a la rama (git push origin feature/AmazingFeature)
  5. Abre un Pull Request

📄 Licencia

Este proyecto está bajo la Licencia MIT - ver el archivo LICENSE para más detalles.

👨‍💻 Autor

Luisma Suarez - GitHub

🙏 Agradecimientos

  • Socket.IO por la excelente librería de WebSockets
  • Comunidad de Node.js por las mejores prácticas
  • Todos los contribuidores del proyecto