0
0
NestJSframework~30 mins

Event handling in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Event Handling in NestJS
📖 Scenario: You are building a simple notification system in a NestJS application. When a new user registers, the system should emit an event and handle it to send a welcome message.
🎯 Goal: Create a NestJS event emitter and listener to handle user registration events and send a welcome notification.
📋 What You'll Learn
Create an event payload interface for user data
Set up an event emitter service to emit user registration events
Create an event listener to handle the registration event
Log a welcome message when the event is handled
💡 Why This Matters
🌍 Real World
Event handling is common in backend applications to decouple actions, such as sending notifications after user actions.
💼 Career
Understanding event-driven architecture and NestJS event handling is valuable for backend developers working with scalable and maintainable applications.
Progress0 / 4 steps
1
Create User Registration Event Payload
Create an interface called UserRegisteredEvent with two string properties: username and email.
NestJS
Need a hint?

Interfaces in TypeScript define the shape of an object. Use interface UserRegisteredEvent { username: string; email: string; }.

2
Set Up Event Emitter Service
Create a class called UserEventsService that injects EventEmitter2 from @nestjs/event-emitter. Add a method emitUserRegistered that takes a UserRegisteredEvent parameter and emits an event named user.registered with the event data.
NestJS
Need a hint?

Use dependency injection to get EventEmitter2. Then call emit with the event name and data.

3
Create Event Listener for User Registration
Create a class called UserEventsListener with a method handleUserRegistered that listens to the user.registered event using the @OnEvent('user.registered') decorator. The method should accept a UserRegisteredEvent parameter.
NestJS
Need a hint?

Use the @OnEvent decorator to listen to events. The method receives the event data as a parameter.

4
Log Welcome Message in Event Listener
Inside the handleUserRegistered method of UserEventsListener, add a console.log statement that outputs: Welcome, {username}! Your email is {email}. using the event data.
NestJS
Need a hint?

Use a template string with backticks to include variables inside the message.