채팅 나가기 API 추가

방장은 나가기 안됨. 추방만 가능.

채팅 서버에서는 그저 탈퇴하고자 하는 사람이 방장인지만 확인함.

// 기존 사용자 그룹에서 제거 API에서 JWT 관련 로직만 제거함
// 사용자 채팅에서 제거 (강퇴, 탈퇴 처리)
const leaveFromChat = asyncHandler(async (req: Request, res: Response) => {
  try {
    const { studyId, userId, type } = req.body;
    const objectChatId = toObjectHexString(studyId) as string;
    const objectUserId = toObjectHexString(userId) as string;
    if (objectChatId && objectUserId) {
      const updatedGroupChat = await chatService.leaveFromChat(objectChatId, objectUserId);
      res.status(200).json(updatedGroupChat);
    }
  } catch (error: any) {
    errorLoggerMiddleware(error as IError, req, res);
    res.status(error.statusCode).json(error.message);
  }
});
// 사용자 채팅 로직 임의 추가
// 사용자 채팅에서 제거 (강퇴, 탈퇴 처리)
// 채팅에 남은 사용자가 없을 경우. 채팅방 삭제
const leaveFromChat = async (chatId: string, userId: string, transfer: string|null) => { 
  const isAddedUserChat = await Chat.findOne({ _id: chatId, isGroupChat: true, users: userId });

  if (!isAddedUserChat) {
    const error = new Error("해당 채팅방 없거나 방장 아닌 유저 또는 해당 방에 유저없음") as IError;
    error.statusCode = 409;
    throw error; 
  }else if(isAddedUserChat.groupAdmin._id.toString() === userId &&
    transfer === null){
    console.log("방장 양도")
    const error = new Error("방장은 양도할 유저를 선택해야 채팅방을 나갈 수 있습니다.") as IError;
    error.statusCode = 409;
    throw error; 
  }else {
    console.log(isAddedUserChat.groupAdmin._id);
    console.log(userId);
    const updateChat = await Chat.findByIdAndUpdate(
      chatId,
      {
          $pull: { users: userId },
        },
        {
          new: true,
        }
      ).where({ isGroupChat: true })
        .populate("users", "-password")
    
    if (!updateChat) {
      const error = new Error("그륩 채팅 조회 실패") as IError;
      error.statusCode = 404;
      throw error;
    } else {
      if (updateChat?.users.length == 0) {
        const res = await Chat.updateOne({ _id: chatId }, { $set: { isDeleted: true } });
      }
      return updateChat;
    }
  }
}

채팅 삭제 API

// 로직에서 $pull이 아닌 $set으로 isDelete만 true로 변경하고있다. 
// 이유를 알 필요가 있다.
const deleteChat = async (chatId: string, userId: string) => {
  const isChat = await Chat.findOne({ groupAdmin: userId, isGroupChat: true });

  
  if (!isChat) {
    const error = new Error("방장 아님") as IError;
    error.statusCode = 409;
    throw error;
  } else {
    const deletedChat = await Chat.updateOne({ _id: chatId }, { $set: { isDeleted: true } });
    if (!deletedChat) {
      const error = new Error("채팅 조회 삭제실패") as IError;
      error.statusCode = 500;
      throw error;
    }
    return deletedChat;
  }
}

채팅 수정 api 생성 ⇒ 채팅방 이름 변경