feat: handle notification async using event emitter

This commit is contained in:
Abdalhamid Alhamad
2024-12-29 11:44:51 +03:00
parent 5663a287f9
commit f383f6d14d
13 changed files with 57 additions and 15 deletions

View File

@ -1,7 +1,12 @@
import { Injectable } from '@nestjs/common';
import { forwardRef, Inject, Injectable } from '@nestjs/common';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';
import { DeviceService } from '~/auth/services';
import { PageOptionsRequestDto } from '~/core/dtos';
import { OTP_BODY, OTP_TITLE } from '../../otp/constants';
import { OtpType } from '../../otp/enums';
import { ISendOtp } from '../../otp/interfaces';
import { Notification } from '../entities';
import { EventType, NotificationChannel, NotificationScope } from '../enums';
import { NotificationsRepository } from '../repositories';
import { FirebaseService } from './firebase.service';
import { TwilioService } from './twilio.service';
@ -9,10 +14,11 @@ import { TwilioService } from './twilio.service';
@Injectable()
export class NotificationsService {
constructor(
private readonly deviceService: DeviceService,
private readonly firebaseService: FirebaseService,
private readonly notificationRepository: NotificationsRepository,
private readonly twilioService: TwilioService,
private readonly eventEmitter: EventEmitter2,
@Inject(forwardRef(() => DeviceService)) private readonly deviceService: DeviceService,
) {}
async sendPushNotification(userId: string, title: string, body: string) {
@ -47,4 +53,26 @@ export class NotificationsService {
markAsRead(userId: string) {
return this.notificationRepository.markAsRead(userId);
}
async sendOtpNotification(sendOtpRequest: ISendOtp, otp: string) {
const notification = await this.createNotification({
recipient: sendOtpRequest.recipient,
title: OTP_TITLE,
message: OTP_BODY.replace('{otp}', otp),
scope: NotificationScope.OTP,
channel: sendOtpRequest.otpType === OtpType.EMAIL ? NotificationChannel.EMAIL : NotificationChannel.SMS,
});
return this.eventEmitter.emit(EventType.NOTIFICATION_CREATED, notification);
}
@OnEvent(EventType.NOTIFICATION_CREATED)
handleNotificationCreatedEvent(notification: Notification) {
switch (notification.channel) {
case NotificationChannel.SMS:
return this.sendSMS(notification.recipient!, notification.message);
case NotificationChannel.PUSH:
return this.sendPushNotification(notification.userId, notification.title, notification.message);
}
}
}