Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/trs/nestjs-events
Alternative event module for NestJS.
https://github.com/trs/nestjs-events
hacktoberfest
Last synced: 23 days ago
JSON representation
Alternative event module for NestJS.
- Host: GitHub
- URL: https://github.com/trs/nestjs-events
- Owner: trs
- Created: 2023-02-25T22:57:45.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2024-02-08T19:51:33.000Z (11 months ago)
- Last Synced: 2024-12-12T00:44:24.783Z (27 days ago)
- Topics: hacktoberfest
- Language: TypeScript
- Homepage:
- Size: 1010 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# NestJS Events
Alternative event module for NestJS.
## Install
```sh
yarn add nestjs-events
````nestjs-events` works with NestJS (9 or 10) and RxJS 7, ensure your have those installed.
```sh
yarn add @nestjs/common@^10 rxjs@^7
```## Usage
Register the event module in your app to be available globally
```ts
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
```ts
import { Module } from "@nestjs/common";
import { EventModule } from "nestjs-events";@Module({
imports: [
EventModule.register({
prefix: "", // optional
}),
],
})
export class MyOtherModule {}
```Declare your events.
```ts
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.
```ts
import { EventBuilder } from "nestjs-events";export class MyEvent extends EventBuilder<{ value: number; other: string }>() {}
```Emit events with the `EventService`.
```ts
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.
```ts
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.
```ts
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();
}
}
```