feat: add smtp and fix dynamic link

This commit is contained in:
Abdalhamid Alhamad
2025-01-06 16:46:35 +03:00
parent 25ef549417
commit 3ab0f179d8
11 changed files with 123 additions and 21 deletions

View File

@ -1,3 +1,4 @@
import { MailerService } from '@nestjs-modules/mailer';
import { Injectable, Logger } from '@nestjs/common';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';
import { PageOptionsRequestDto } from '~/core/dtos';
@ -5,6 +6,7 @@ import { DeviceService } from '~/user/services';
import { OTP_BODY, OTP_TITLE } from '../../otp/constants';
import { OtpType } from '../../otp/enums';
import { ISendOtp } from '../../otp/interfaces';
import { SendEmailRequestDto } from '../dtos/request';
import { Notification } from '../entities';
import { EventType, NotificationChannel, NotificationScope } from '../enums';
import { NotificationsRepository } from '../repositories';
@ -20,6 +22,7 @@ export class NotificationsService {
private readonly twilioService: TwilioService,
private readonly eventEmitter: EventEmitter2,
private readonly deviceService: DeviceService,
private readonly mailerService: MailerService,
) {}
async sendPushNotification(userId: string, title: string, body: string) {
@ -41,6 +44,17 @@ export class NotificationsService {
await this.twilioService.sendSMS(to, body);
}
async sendEmail({ to, subject, data, template }: SendEmailRequestDto) {
this.logger.log(`Sending email to ${to}`);
await this.mailerService.sendMail({
to,
subject,
template,
context: { ...data },
});
this.logger.log(`Email sent to ${to}`);
}
async getNotifications(userId: string, pageOptionsDto: PageOptionsRequestDto) {
this.logger.log(`Getting notifications for user ${userId}`);
const [[notifications, count], unreadCount] = await Promise.all([
@ -78,8 +92,17 @@ export class NotificationsService {
return this.eventEmitter.emit(EventType.NOTIFICATION_CREATED, notification);
}
private getTemplateFromNotification(notification: Notification) {
switch (notification.scope) {
case NotificationScope.OTP:
return 'otp';
default:
return 'otp';
}
}
@OnEvent(EventType.NOTIFICATION_CREATED)
handleNotificationCreatedEvent(notification: Notification) {
handleNotificationCreatedEvent(notification: Notification, data?: any) {
this.logger.log(
`Handling ${EventType.NOTIFICATION_CREATED} event for notification ${notification.id} and type ${notification.channel}`,
);
@ -88,6 +111,13 @@ export class NotificationsService {
return this.sendSMS(notification.recipient!, notification.message);
case NotificationChannel.PUSH:
return this.sendPushNotification(notification.userId, notification.title, notification.message);
case NotificationChannel.EMAIL:
return this.sendEmail({
to: notification.recipient!,
subject: notification.title,
data,
template: this.getTemplateFromNotification(notification),
});
}
}
}