chore: implement notification module

This commit is contained in:
Matin
2025-02-08 11:56:56 +03:30
parent e216937dd9
commit 786ea465ff
12 changed files with 205 additions and 7 deletions
@@ -0,0 +1,65 @@
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
import { PaginationDto } from "../../../common/DTO/pagination.dto";
import { NotificationMessage, UserMessage } from "../../../common/enums/message.enum";
import { UsersService } from "../../users/providers/users.service";
import { PaginationUtils } from "../../utils/providers/pagination.utils";
import { CreateNotificationDto } from "../DTO/create-notification.dto";
import { NotificationRepository } from "../repositories/notifications.repository";
@Injectable()
export class NotificationsService {
constructor(
private readonly notificationRepository: NotificationRepository,
private readonly usersService: UsersService,
) {}
//************************ */
async createNotification(createNotificationDto: CreateNotificationDto) {
const { user } = await this.usersService.findOneById(createNotificationDto.recipientId);
if (!user) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
const notification = this.notificationRepository.create({
...createNotificationDto,
recipient: user,
});
await this.notificationRepository.save(notification);
return { notification };
}
//************************ */
async markAsRead(notificationId: string, userId: string) {
const notification = await this.notificationRepository.findOne({
where: { id: notificationId, recipient: { id: userId } },
});
if (!notification) throw new NotFoundException(NotificationMessage.NOTIFICATION_NOT_FOUND_OR_ACCESS_DENIED);
notification.isRead = true;
return this.notificationRepository.save(notification);
}
//************************ */
async createLoginNotification(recipientId: string) {
const message = NotificationMessage.LOGIN_MESSAGE.replace("[DATE]", new Date().toLocaleString("fa-IR"));
return this.createNotification({ title: NotificationMessage.LOGIN, message, recipientId });
}
//************************ */
async getAllNotifications(paginationDto: PaginationDto, recipientId: string) {
const { skip, limit } = PaginationUtils(paginationDto);
const [notifications, count] = await this.notificationRepository
.createQueryBuilder("notification")
.where("notification.recipientId = :recipientId", { recipientId })
.orderBy("notification.createdAt", "DESC")
.skip(skip)
.take(limit)
.getManyAndCount();
return { notifications, count, paginate: true };
}
}