Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 3 additions & 16 deletions src/modules/chat/chat.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@ import TransactionManager from 'src/providers/database/transaction/transaction.m

@Injectable()
export default class ChatRepository {
constructor(
@InjectModel(ChatRoom.name) private chatRoom: Model<ChatRoom>,
@InjectModel(Chat.name) private chat: Model<Chat>
) {}
constructor(@InjectModel(Chat.name) private chat: Model<Chat>) {}

async findChatsByChatRoomId(options: ChatQueryOptions): Promise<IChat[]> {
const { chatRoomId, page, pageSize } = options;
Expand Down Expand Up @@ -44,7 +41,7 @@ export default class ChatRepository {
const { senderId, chatRoomId, content, type } = data.toDB();
const session = TransactionManager.getMongoSession();

const chat = await this.chat.create(
const [chat] = await this.chat.create(
[
{
senderId,
Expand All @@ -56,17 +53,7 @@ export default class ChatRepository {
{ session }
);

const chatRoom = await this.chatRoom.updateOne(
{ _id: chatRoomId },
{ $push: { chatIds: chat[0]._id } },
{ session }
);
if (chatRoom.modifiedCount === 0) {
throw new InternalServerError(ErrorMessage.INTERNAL_SERVER_ERROR_CHAT_ROOM_UPDATE);
}

const domainChat = new ChatMapper(chat[0]).toDomain();

const domainChat = new ChatMapper(chat).toDomain();
return domainChat;
}

Expand Down
14 changes: 7 additions & 7 deletions src/modules/chat/chat.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import Transactional from 'src/common/decorators/transaction.decorator';
@Injectable()
export default class ChatService {
constructor(
private readonly chatRepository: ChatRepository,
private readonly repository: ChatRepository,
private readonly s3Service: S3Service,
private readonly transactionManager: TransactionManager,
@Inject(forwardRef(() => ChatRoomService)) private readonly chatRoomService: ChatRoomService
Expand All @@ -29,8 +29,8 @@ export default class ChatService {
options: ChatQueryOptions
): Promise<{ totalCount: number; list: ChatToClientProperties[] }> {
const [totalCount, list] = await Promise.all([
this.chatRepository.totalCount(options.chatRoomId),
this.chatRepository.findChatsByChatRoomId(options)
this.repository.totalCount(options.chatRoomId),
this.repository.findChatsByChatRoomId(options)
]);

const toClientListPromise = list?.map((chat) => this.convertToClient(chat.toClient()));
Expand All @@ -40,7 +40,7 @@ export default class ChatService {

async getChatDomain(data: { id: string; userId?: string }) {
const { id, userId } = data || {};
const chat = await this.chatRepository.findChatById(id);
const chat = await this.repository.findChatById(id);

if (!chat) {
throw new NotFoundError(ErrorMessage.CHAT_NOT_FOUND_ERROR);
Expand All @@ -66,7 +66,7 @@ export default class ChatService {

async postChat(data: ChatCreateData): Promise<ChatToClientProperties> {
const chatData = Chat.create(data);
const chat = await this.chatRepository.createChat(chatData);
const chat = await this.repository.createChat(chatData);
const convertChat = await this.convertToClient(chat.toClient());

return convertChat;
Expand All @@ -76,7 +76,7 @@ export default class ChatService {
const chatData = Chat.create(data);
const s3key = await this.s3Service.uploadFile(chatData.toS3());
chatData.setS3Key(s3key);
const chat = await this.chatRepository.createChat(chatData);
const chat = await this.repository.createChat(chatData);
const convertChat = await this.convertToClient(chat.toClient(), true);
return convertChat;
}
Expand All @@ -98,7 +98,7 @@ export default class ChatService {
const isActive = await this.chatRoomService.getIsActiveById(chatRoomId);
if (!isActive) throw new BadRequestError(ErrorMessage.CHAT_ROOM_NOT_IS_ACTIVE);

await this.chatRepository.delete(id);
await this.repository.delete(id);
}

private handleDeletedMessage(chatData: ChatToClientProperties): ChatToClientProperties {
Expand Down
33 changes: 23 additions & 10 deletions src/modules/chatRoom/chatRoom.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { ChatQueryOptions } from 'src/modules/chat/types/chat.type';
import { FindChatRoomByIdOptions } from 'src/modules/chatRoom/types/chatRoom.type';
import { ChatRoom } from 'src/providers/database/mongoose/chatRoom.schema';
import { ObjectId } from 'mongodb';
import TransactionManager from 'src/providers/database/transaction/transaction.manager';

@Injectable()
export default class ChatRoomRepository {
Expand Down Expand Up @@ -36,11 +37,13 @@ export default class ChatRoomRepository {

async findChatRoom(options: FindChatRoomByIdOptions): Promise<IChatRoom> {
const { chatRoomId, planId } = options || {};
const session = TransactionManager.getMongoSession();

const chatRoom = await this.chatRoom
.findOne({
$or: [{ _id: chatRoomId }, { planId }]
})
.session(session)
.exec();

const domainChatRoom = new ChatRoomMapper(chatRoom).toDomain();
Expand All @@ -53,23 +56,33 @@ export default class ChatRoomRepository {
}

async createChatRoom(data: IChatRoom): Promise<IChatRoom> {
const session = TransactionManager.getMongoSession();
const { userIds, planId, planTitle, planTripDate, quotePrice } = data.toDB();
const chatRoom = await this.chatRoom.create({
planId,
planTitle,
planTripDate,
quotePrice,
userIds,
chatIds: []
});
const [chatRoom] = await this.chatRoom.create(
[
{
planId,
planTitle,
planTripDate,
quotePrice,
userIds,
chatIds: []
}
],
{ session }
);

const domainChatRoom = new ChatRoomMapper(chatRoom).toDomain();
return domainChatRoom;
}

async update(data: IChatRoom): Promise<IChatRoom> {
const { planId, isActive } = data.toDB();
const chatRoom = await this.chatRoom.findOneAndUpdate({ planId }, { isActive }, { new: true });
const session = TransactionManager.getMongoSession();
const { planId, isActive, addChatId } = data.toDB();

const chatRoom = await this.chatRoom
.findOneAndUpdate({ planId }, { isActive, $addToSet: { chatIds: { $each: [addChatId] } } }, { new: true })
.session(session);
const domainChatRoom = new ChatRoomMapper(chatRoom).toDomain();
return domainChatRoom;
}
Expand Down
32 changes: 19 additions & 13 deletions src/modules/chatRoom/chatRoom.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,17 @@ import { ChatReference, FileUploadData, FindChatRoomByIdOptions } from 'src/modu
import NotFoundError from 'src/common/errors/notFoundError';
import IChatRoom from './domain/chatRoom.interface';
import BadRequestError from 'src/common/errors/badRequestError';
import TransactionManager from 'src/providers/database/transaction/transaction.manager';
import Transactional from 'src/common/decorators/transaction.decorator';

@Injectable()
export default class ChatRoomService {
private readonly connectedClients = new Map<string, Socket>();
constructor(
private readonly chatRoomRepository: ChatRoomRepository,
private readonly repository: ChatRoomRepository,
private readonly chatService: ChatService,
private readonly userService: UserService
private readonly userService: UserService,
private readonly transactionManager: TransactionManager
) {}

registerClient(userId: string, client: Socket) {
Expand All @@ -44,21 +46,21 @@ export default class ChatRoomService {
}

async getChatRooms(options: ChatQueryOptions): Promise<{ totalCount: number; list: ChatRoomWithUserInfo[] }> {
const totalCount = await this.chatRoomRepository.totalCount(options.userId);
const list = await this.chatRoomRepository.findManyChatRooms(options);
const totalCount = await this.repository.totalCount(options.userId);
const list = await this.repository.findManyChatRooms(options);
const toClientList = await Promise.all(list?.map((chatRoom) => this.fetchAndFormatUserInfo(chatRoom.toClient())));

return { list: toClientList, totalCount };
}

async getActiveChatRoomIds(userId: string): Promise<string[]> {
const chatRoomIds = await this.chatRoomRepository.findActiveChatRoomIdsByUserId(userId);
const chatRoomIds = await this.repository.findActiveChatRoomIdsByUserId(userId);
return chatRoomIds;
}

async getChatRoomDomain(options: FindChatRoomByIdOptions): Promise<IChatRoom> {
const { userId } = options || {};
const chatRoom = await this.chatRoomRepository.findChatRoom(options);
const chatRoom = await this.repository.findChatRoom(options);

if (!chatRoom) {
throw new NotFoundError(ErrorMessage.CHAT_ROOM_NOTFOUND);
Expand Down Expand Up @@ -91,13 +93,15 @@ export default class ChatRoomService {
return { totalCount, list };
}

@Transactional()
async postChatRoom(data: ChatRoomProperties): Promise<void> {
const chatRoomData = ChatRoom.create(data);
const isChatRoom = await this.chatRoomRepository.findChatRoom({ planId: data.planId });
if (!isChatRoom) await this.chatRoomRepository.createChatRoom(chatRoomData);
const isChatRoom = await this.repository.findChatRoom({ planId: data.planId });
if (!isChatRoom) await this.repository.createChatRoom(chatRoomData);
//NOTE. 로직상 채팅방이 이미 있으면 안되지만 개발상의 편의를 위해 추가
}

@Transactional()
async postChat(data: ChatCreateData): Promise<ChatToClientProperties> {
const { senderId, chatRoomId } = data;

Expand All @@ -106,6 +110,8 @@ export default class ChatRoomService {
if (chatRoom.getIsActive() === false) throw new BadRequestError(ErrorMessage.CHAT_ROOM_NOT_IS_ACTIVE);

const chatData = await this.chatService.postChat(data);
chatRoom.update({ chatId: chatData.id });
await this.repository.update(chatRoom);
await this.sendMessageToChatRoom(chatData);

return chatData;
Expand All @@ -121,17 +127,17 @@ export default class ChatRoomService {
return chatData;
}

@Transactional()
async deActive(planId: string): Promise<void> {
const chatRoom = await this.chatRoomRepository.findChatRoom({ planId });
//NOTE. 일단 임시로 트랜젝션을 제외
const chatRoom = await this.repository.findChatRoom({ planId });
if (chatRoom) {
chatRoom.update();
await this.chatRoomRepository.update(chatRoom);
chatRoom.update({ deActive: true });
await this.repository.update(chatRoom);
} //NOTE. 채팅방 목데이터가 없어서 나는 에러 처리
}

async deActiveMany(planIds: string[]): Promise<void> {
await this.chatRoomRepository.updateMany(planIds);
await this.repository.updateMany(planIds);
}

async sendMessageToChatRoom(chat: ChatReference) {
Expand Down
9 changes: 6 additions & 3 deletions src/modules/chatRoom/domain/chatRoom.domain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export default class ChatRoom implements IChatRoom {
private chatIds: string[];
private lastChat: string;
private isActive?: boolean;
private addChatId: string;

constructor(private chatRoom: ChatRoomProperties) {
this.id = chatRoom.id;
Expand All @@ -41,7 +42,8 @@ export default class ChatRoom implements IChatRoom {
planTitle: this.planTitle,
planTripDate: this.planTripDate,
quotePrice: this.quotePrice,
isActive: this.isActive
isActive: this.isActive,
addChatId: this.addChatId
};
}

Expand All @@ -60,8 +62,9 @@ export default class ChatRoom implements IChatRoom {
};
}

update(): void {
this.isActive = false;
update(data: { deActive: boolean; chatId: string }): void {
if (data.deActive) this.isActive = false;
if (data.chatId) this.addChatId = data.chatId;
}

getId(): string {
Expand Down
2 changes: 1 addition & 1 deletion src/modules/chatRoom/domain/chatRoom.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { ChatRoomProperties } from './chatRoom.properties';
export default interface IChatRoom {
toDB(): ChatRoomProperties;
toClient(): ChatRoomProperties;
update(): void;
update(data: { deActive?: boolean; chatId?: string }): void;
getId(): string;
getUserIds(): string[];
getIsActive(): boolean;
Expand Down
1 change: 1 addition & 0 deletions src/modules/chatRoom/domain/chatRoom.properties.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export interface ChatRoomProperties {
chatIds?: string[] | { content: string; type: ChatType };
lastChat?: string;
isActive?: boolean;
addChatId?: string;
}

export interface ChatRoomWithUserInfo {
Expand Down
16 changes: 14 additions & 2 deletions src/modules/plan/plan.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ export default class PlanService {
return plan.toClientWithAddress();
}

@Transactional()
async postQuote(data: CreateOptionalQuoteData, userId: string, planId: string): Promise<QuoteToClientProperties> {
const plan = await this.repository.findById(planId);

Expand All @@ -164,6 +165,7 @@ export default class PlanService {
return quote;
}

@Transactional()
async requestPlanAssign(data: AssignData): Promise<PlanToClientProperties> {
const { id, userId, assigneeId } = data;
const plan = await this.repository.findById(data.id);
Expand Down Expand Up @@ -199,6 +201,7 @@ export default class PlanService {
return updatedPlan.toClient();
}

@Transactional()
async rejectPlanAssign(data: AssignData): Promise<PlanToClientProperties> {
const plan = await this.repository.findById(data.id);

Expand All @@ -210,11 +213,18 @@ export default class PlanService {
const updatedPlan = await this.repository.update(plan);

const makerNickName = plan.getAssigneeNickName(data.assigneeId);
const dreamerNickName = plan.getDreamerNickName();
const dreamerId = plan.getDreamerId();
const planTitle = plan.getTitle();
// this.eventEmitter.emit('notification', {
// userId: data.assigneeId,
// event: NotificationEventName.REJECT_REQUEST,
// payload: { nickName: makerNickName, planTitle }
// });
this.eventEmitter.emit('notification', {
userId: data.assigneeId,
userId: dreamerId,
event: NotificationEventName.REJECT_REQUEST,
payload: { nickName: makerNickName, planTitle }
payload: { nickName: dreamerNickName, planTitle }
});

return updatedPlan.toClient();
Expand Down Expand Up @@ -299,7 +309,9 @@ export default class PlanService {
if (plan.getStatus() === StatusValues.CONFIRMED) {
throw new BadRequestError(ErrorMessage.PLAN_DELETE_BAD_REQUEST);
}
const quotes = plan.getQuoteIds();

await this.quoteService.deleteManyQuotes(id);
const deletedPlan = await this.repository.delete(id);

const dreamerNickName = deletedPlan.getDreamerNickName();
Expand Down
Loading