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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@ap-dev/nestjs-events

v0.1.12

Published

A NestJS events library with RabbitMQ integration

Readme

NestJS Events Library

Una librería de eventos para NestJS con soporte opcional para RabbitMQ que proporciona una interfaz simple y potente para el manejo de mensajería asíncrona.

Características

  • ✅ Integración nativa con NestJS
  • ✅ Soporte opcional para RabbitMQ
  • ✅ Configuración flexible (síncrona y asíncrona)
  • ✅ Interfaz única y consistente (EventsService)
  • ✅ Manejo de colas y exchanges
  • ✅ Consumo de mensajes con acknowledgments
  • ✅ Gestión automática de conexiones
  • ✅ Logging integrado
  • ✅ TypeScript con tipado completo
  • ✅ Fácil migración entre proveedores de mensajería

Instalación

npm install @ap-dev/nestjs-events

Configuración

Configuración Básica (sin RabbitMQ)

import { Module } from '@nestjs/common';
import { EventsModule } from '@ap-dev/nestjs-events';

@Module({
  imports: [
    EventsModule.forRoot(), // Sin configuración = solo logging local
  ],
})
export class AppModule {}

Configuración con RabbitMQ

import { Module } from '@nestjs/common';
import { EventsModule } from '@ap-dev/nestjs-events';

@Module({
  imports: [
    EventsModule.forRoot({
      rabbitmq: {
        url: 'amqp://localhost:5672',
        prefetch: 10,
      },
    }),
  ],
})
export class AppModule {}

Configuración Asíncrona

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { EventsModule } from '@ap-dev/nestjs-events';

@Module({
  imports: [
    ConfigModule.forRoot(),
    EventsModule.forRootAsync({
      useFactory: async (configService: ConfigService) => ({
        rabbitmq: {
          url: configService.get<string>('RABBITMQ_URL', 'amqp://localhost:5672'),
          prefetch: configService.get<number>('RABBITMQ_PREFETCH', 10),
        },
      }),
      inject: [ConfigService],
    }),
  ],
})
export class AppModule {}

Uso

Uso Básico

import { Injectable } from '@nestjs/common';
import { EventsService } from '@ap-dev/nestjs-events';

@Injectable()
export class MyService {
  constructor(private readonly eventsService: EventsService) {}

  async sendUserCreatedEvent(user: any) {
    // Emite un evento (se enviará a RabbitMQ si está configurado)
    await this.eventsService.emitEvent('user.created', user);
  }

  async sendToSpecificQueue(data: any) {
    // Envía directamente a una cola específica
    await this.eventsService.sendToQueue('notifications', data);
  }

  async publishToExchange(data: any) {
    // Publica a un exchange con routing key
    await this.eventsService.publishToExchange('user-events', 'user.updated', data);
  }

  async checkConnection() {
    // Verifica si RabbitMQ está habilitado y conectado
    const isEnabled = this.eventsService.isRabbitMQEnabled();
    const isConnected = this.eventsService.isConnected();
    
    console.log(`RabbitMQ enabled: ${isEnabled}, connected: ${isConnected}`);
  }
}

Configuración de Infraestructura

import { Injectable, OnModuleInit } from '@nestjs/common';
import { EventsService } from '@ap-dev/nestjs-events';

@Injectable()
export class InfrastructureService implements OnModuleInit {
  constructor(private readonly eventsService: EventsService) {}

  async onModuleInit() {
    if (this.eventsService.isRabbitMQEnabled()) {
      await this.setupInfrastructure();
    }
  }

  private async setupInfrastructure() {
    // Crear exchange
    await this.eventsService.createExchange('user-events', {
      type: 'topic',
      durable: true,
    });

    // Crear cola
    await this.eventsService.createQueue('user-notifications', {
      durable: true,
      arguments: { 'x-message-ttl': 60000 },
    });

    // Vincular cola al exchange con routing key
    await this.eventsService.bindQueueToExchange(
      'user-notifications',
      'user-events',
      'user.*'
    );
  }
}

Consumo de Mensajes

import { Injectable } from '@nestjs/common';
import { EventsService } from '@ap-dev/nestjs-events';

@Injectable()
export class ConsumerService {
  constructor(private readonly eventsService: EventsService) {}

  async startConsumer() {
    if (!this.eventsService.isConnected()) {
      console.log('RabbitMQ not connected, skipping consumer setup');
      return;
    }

    // Consumir mensajes
    const consumerTag = await this.eventsService.consume(
      'user-notifications',
      (message, ack, nack) => {
        try {
          console.log('Received:', message.content);
          ack(); // Confirmar procesamiento
        } catch (error) {
          console.error('Error processing message:', error);
          nack(true); // Rechazar y reencolar
        }
      },
      { noAck: false }
    );

    console.log('Consumer started with tag:', consumerTag);
  }
}

Ejemplos de Configuración

Variables de Entorno

# .env
RABBITMQ_URL=amqp://user:password@localhost:5672
RABBITMQ_QUEUE=events
RABBITMQ_EXCHANGE=app-events
RABBITMQ_ROUTING_KEY=app

Configuración con Docker

# docker-compose.yml
version: '3.8'
services:
  rabbitmq:
    image: rabbitmq:3-management
    ports:
      - "5672:5672"
      - "15672:15672"
    environment:
      RABBITMQ_DEFAULT_USER: admin
      RABBITMQ_DEFAULT_PASS: password

Interfaces Disponibles

interface RabbitMQConfig {
  url: string;
  queue?: string;
  exchange?: string;
  routingKey?: string;
  exchangeType?: 'direct' | 'topic' | 'fanout' | 'headers';
  durable?: boolean;
  persistent?: boolean;
  prefetch?: number;
}

interface MessageOptions {
  queue?: string;
  exchange?: string;
  routingKey?: string;
  persistent?: boolean;
  priority?: number;
  expiration?: string;
  headers?: Record<string, any>;
}

Desarrollo

Construir la librería

npm run build

Ejecutar tests

npm test

Publicar

npm publish

Licencia

MIT