mirror of
https://github.com/HamzaSha1/zod-backend.git
synced 2025-11-26 08:34:55 +00:00
feat: handle notification async using event emitter
This commit is contained in:
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user