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

@byal-boilerplate/event-emitter

v0.0.1

Published

This library can be used to send and handle events. It provides an abstraction of a message queue provider like RabbitMQ or Redis.

Downloads

70

Readme

Event Emitter

This library can be used to send and handle events. It provides an abstraction of a message queue provider like RabbitMQ or Redis.

Usage

Import the module

import { Module } from '@nestjs/common';
import { EventEmitter } from '@byal-boilerplate/event-emitter';
import { env } from '../config/env';

@Module({
  imports: [
    EventEmitterModule.forRoot({ queuePrefix: env.APPLICATION_SLUG_NAME }),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

When the API import this library module, it will search for the handlers declared by the @Subscriber() decorator. The handlers will be registered in the event emitter and will be called when an event is received.

Sending events

After importing the module, the event emitter can be injected into a service and used to send events.

import { EventEmitter, TestEvent } from '@byal-boilerplate/event-emitter';
import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  constructor(private readonly eventEmitter: EventEmitter) {}

  async sendEvent() {
    await this.eventEmitter.send(TestEvent, {
      email: '[email protected]',
    });
  }
}

Decorators

@Subscriber(EventType)

This decorator can be used to register a handler for an event. It should be used only in a provider method.

This decorator has one parameter, the event type. The event type must be a class that extends the BaseEvent abstract class and decorated with @RoutingKey(). Next, an example of a subscriber:

import { Subscribe, TestEvent } from '@byal-boilerplate/event-emitter';
import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  @Subscribe(TestEvent)
  handleTestEvent(event: TestEvent) {
    this.logger.debug(`Message received: ${event.payload}`);
  }
}

Each application can have only one handler for each event type. If more than one handler is registered for the same event type, an error will be thrown when the application starts, but the application will continue to run using only the first handler registered.

@RoutingKey('exemple.event')

This decorator can be used to define the routing key of an event. It should be used only in a class that extends the BaseEvent abstract class and inside this library. All contracts events declared in this library are already decorated with this decorator.

import { RoutingKey } from '../../decorators/routing-key.decorator';
import { BaseEvent } from '../base-event';

interface UserCreatedPayload {
  id: string;
  name: string;
}

@RoutingKey('user.created')
export class UserCreatedEvent extends BaseEvent<UserCreatedPayload> {}

Create a new event

To create a new event, you must run the generate command:

nx generate @byal-boilerplate/event-emitter:event

This command will ask you for the following information:

  • Project: The project that is the owner of the event.
  • Event name: The name of the event. This name will be used to create the event file and class name.
  • Routing key: The routing key of the event. This key will be used to identify the event in the message queue.
  • Description: A description of the event.

For example, if you want to create an event called UserUpdated, you must run the following command:

nx generate @byal-boilerplate/event-emitter:event --dryRun                                                                     

>  NX  Generating @byal-boilerplate/event-emitter:event

✔ Which project is the owner of this event · auth-api
✔ What is the name of the event in `kebab-case` · user-updated
✔ What is the event routing key · user.updated
✔ What is the event description · Emitted when an user has changed

The command will return the following output with the created and updated files:

CREATE libs/event-emitter/src/lib/contracts/auth-api/user-updated.ts
UPDATE libs/event-emitter/src/lib/contracts/index.ts

It means that the event file was created in the contracts folder and the index.ts file was updated to export the new event. Now you can use the new event in your application.

Send the event

import { EventEmitter, UserUpdatedEvent } from '@byal-boilerplate/event-emitter';
import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  constructor(private readonly eventEmitter: EventEmitter) {}

  async sendEvent() {
    await this.eventEmitter.send(UserUpdatedEvent, {
      id: 'user-id-123',
    });
  }
}

Handle the event

import { Subscribe, UserUpdatedEvent } from '@byal-boilerplate/event-emitter';
import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  @Subscribe(UserUpdatedEvent)
  handleUserUpdatedEvent(event: UserUpdatedEvent) {
    this.logger.debug(`Message received: ${event.payload}`);
  }
}