chore: implement notification module
This commit is contained in:
@@ -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 };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user