- Reordered and grouped imports consistently in backend and frontend files for better readability. - Applied indentation and formatting fixes across frontend components, services, and backend modules. - Adjusted multiline method calls and type definitions for improved clarity.
57 lines
1.6 KiB
TypeScript
57 lines
1.6 KiB
TypeScript
import { ForbiddenException, Injectable } from "@nestjs/common";
|
|
import { EventsGateway } from "../realtime/events.gateway";
|
|
import type { CreateMessageDto } from "./dto/create-message.dto";
|
|
import { MessagesRepository } from "./repositories/messages.repository";
|
|
|
|
@Injectable()
|
|
export class MessagesService {
|
|
constructor(
|
|
private readonly messagesRepository: MessagesRepository,
|
|
private readonly eventsGateway: EventsGateway,
|
|
) {}
|
|
|
|
async sendMessage(senderId: string, dto: CreateMessageDto) {
|
|
let conversation = await this.messagesRepository.findConversationBetweenUsers(
|
|
senderId,
|
|
dto.recipientId,
|
|
);
|
|
|
|
if (!conversation) {
|
|
const newConv = await this.messagesRepository.createConversation();
|
|
await this.messagesRepository.addParticipant(newConv.id, senderId);
|
|
await this.messagesRepository.addParticipant(newConv.id, dto.recipientId);
|
|
conversation = newConv;
|
|
}
|
|
|
|
const message = await this.messagesRepository.createMessage({
|
|
conversationId: conversation.id,
|
|
senderId,
|
|
text: dto.text,
|
|
});
|
|
|
|
// Notify recipient via WebSocket
|
|
this.eventsGateway.sendToUser(dto.recipientId, "new_message", {
|
|
conversationId: conversation.id,
|
|
message,
|
|
});
|
|
|
|
return message;
|
|
}
|
|
|
|
async getConversations(userId: string) {
|
|
return this.messagesRepository.findAllConversations(userId);
|
|
}
|
|
|
|
async getMessages(userId: string, conversationId: string) {
|
|
const isParticipant = await this.messagesRepository.isParticipant(
|
|
conversationId,
|
|
userId,
|
|
);
|
|
if (!isParticipant) {
|
|
throw new ForbiddenException("You are not part of this conversation");
|
|
}
|
|
|
|
return this.messagesRepository.findMessagesByConversationId(conversationId);
|
|
}
|
|
}
|