Socket
Book a DemoInstallSign in
Socket

nestjs-events

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

nestjs-events

Alternative event module for NestJS.

latest
Source
npmnpm
Version
1.3.1
Version published
Maintainers
1
Created
Source

NestJS Events

Alternative event module for NestJS.

Install

yarn add nestjs-events

nestjs-events works with NestJS (9 or 10) and RxJS 7, ensure your have those installed.

yarn add @nestjs/common@^10 rxjs@^7

Usage

Register the event module in your app to be available globally

import { Module } from "@nestjs/common";
import { EventModule } from "nestjs-events";

@Module({
  imports: [
    EventModule.forRoot({
      prefix: "", // optional
    }),
  ],
})
export class AppModule {}

Or only for a specific module

import { Module } from "@nestjs/common";
import { EventModule } from "nestjs-events";

@Module({
  imports: [
    EventModule.register({
      prefix: "", // optional
    }),
  ],
})
export class MyOtherModule {}

Declare your events.

export class MyEvent {
  public readonly value: number;
  public readonly other: string;

  constructor(parameters: { value: number; other: string }) {
    this.value = parameters.value;
    this.other = parameters.other;
  }
}

You can also use the EventBuilder helper.

import { EventBuilder } from "nestjs-events";

export class MyEvent extends EventBuilder<{ value: number; other: string }>() {}

Emit events with the EventService.

import { Injectable } from "@nestjs/common";
import { EventService } from "nestjs-events";

import { MyEvent } from "./my-event.event.ts";

@Injectable()
export class MyService {
  constructor(private readonly eventService: EventService) {}

  someMethod() {
    this.eventService.emit(new MyEvent({ value: 1, other: "hello" }));
  }
}

Listen to events through the @OnEvent decorator.

import { Injectable } from "@nestjs/common";
import { OnEvent } from "nestjs-events";

import { MyEvent } from "./my-event.event.ts";

@Injectable()
export class MyService {
  @OnEvent(MyEvent)
  handleMyEvent(event: MyEvent) {
    // event.value
    // event.other
  }
}

You can subscribe to events as well, returning an Observable.

import { Injectable } from "@nestjs/common";
import { OnEvent } from "nestjs-events";

import { MyEvent } from "./my-event.event.ts";

@Injectable()
export class MyService {
  constructor(private readonly eventService: EventService) {}

  someMethod() {
    eventService.on(MyEvent).pipe().subscribe();
  }
}

FAQs

Package last updated on 08 Feb 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts