위와 같이 채팅 목록에서 가장 마지막으로 한 채팅을 띄우고자 한다.
채팅방 별로 가장 최근 채팅을 불러오되, 아직 생성된 채팅이 없다면 채팅룸 자체의 생성시간을 띄우겠다.
Part1. 채팅방 별로 가장 마지막 채팅 불러오기
(chat.js)
router.get('/list', isLogin, async (req, res) => {
// chatroom null 일 경우 대비 예외처리
try {
let chatlist = await db
.collection('chatroom')
.find({ member: req.user._id })
.toArray();
console.log('chatlist', chatlist);
let chats = []; // 룸 별로 가장 최근 채팅이 담기는 곳
if (chatlist.length > 0) {
// 각 채팅방의 ObjectId만 따로 분리해 배열로 만듦
const roomIds = chatlist.map((chat) => new ObjectId(chat._id));
console.log('roomids', roomIds);
// 모든 채팅방에 대한 최신 메시지를 가져오기
for (let i = 0; i < roomIds.length; i++) {
const latestChat = await db
.collection('chat')
.find({ roomId: roomIds[i] })
.sort({ date: -1 })
.limit(1)
.toArray();
console.log('latestChat', latestChat);
if (latestChat.length > 0) {
chats.push(latestChat[0]);
}
}
console.log('chats', chats);
// 현재 로그인한 유저가 속한 채팅방들을 꺼내어 Chalist로 렌더링
res.render('chatList.ejs', {
chatlist: chatlist,
loginUser: req.user._id,
lastChat: chats,
});
}
} catch (e) {
console.error(e);
res.status(500).send('Internal Server Error');
}
});
사고과정
1. req.user.id를 기준으로 로그인 한 유저가 멤버로 소속된 chatroom을 모두 가져온다.
2. chatlist 에서 map을 이용하여 `_id` 만 잘라내어 새로운 배열 roomIds를 만든다.
const roomIds = chatlist.map((chat) => new ObjectId(chat._id))
3. roomId를 기준 chat 에 소속된 모든 채팅을 불러오되, sort({date:-1}) 와 limit(1) 을 기준으로 가장 최근 채팅 1개를 룸 마다 가져온다.
4. chats=[] <- 룸마다 가장 최근 채팅이 담기는 곳인 배열에 `latestChat` 의 첫번째 채팅을 push해 집어넣는다.
5. ejs 파일에서 lastChat을 불러온다.
Part2. 생성된 채팅이 없으면 채팅룸 자체 생성시간 불러오기
위와 같이(글 제목: 111), 아직 유저간에 채팅을 시작하지 않은 경우
채팅목록에는 있지만 생성된 채팅은 없으므로 대신 채팅룸 자체가 생성된 시간을 보여주고자 한다.
포인트1. `toLocaleString('ko-KR')` 옵션 지정하기
2024.1.6. 오후 4:35:21
1/6/2024, 4:39:40 PM
- 그 전에, 시간이 위와 같이 다른 형식으로 찍히는 경우가 있는데 이때는 `new Date()` 함수 사용시에 `toLocaleString('ko-KR')` 값을 주면 간단하게 해결할 수 있다.
- date: new Date().toLocaleString('ko-KR')`
포인트2. lastChat 존재 여부에 따라 채팅룸 생성시간 숨기거나 보이게 하기
시작한 채팅이 없어 채팅목록에 채팅 생성시간을 띄울 수 없는 경우, 채팅룸 자체 생성시간을 가져오는데, 경우의 수를 들어 생각해보자.
1. 채팅룸 별로 마지막 채팅 시간을 가져온다.(윗줄)
2. 채팅룸 자체 생성시간을 가져온다. (아랫줄)
3. 마지막 채팅이 있으면 (contentBoxExists = true) 2번을 display none으로 설정한다.
4. 마지막 채팅이 없으면(contentBoxExists = false) 2번을 display block으로 설정한다.
작성코드
(chatList.ejs)
<!-- true,false state 값으로 첫번째 chat이 없는 경우 방지하는 법 -->
<% let contentBoxExists = false %>
<% for(let j=0; j<lastChat.length; j++) { %>
<% if (lastChat[j].roomId.equals(chatlist[i]._id)) { %>
<% contentBoxExists = true %>
<div class="contentBox">
<p class="lastChat"><%= lastChat[j].chats %></p>
<p class="lastChat-date"><%= lastChat[j].date %></p>
</div>
<% } %>
<% } %>
<!-- 콘텐츠 부분(첫번째 chat이 없으면 chatroom이 생성된 시간을 불러옴) -->
<div class="noFirstChat">
<p><%=chatlist[i].date %></p>
</div>
(수정)
<%=chatlist[i].date %> 이 코드를 다음과 같이 수정한다.
<div class="noFirstChat">
<!-- <p><%=chatlist[i].date %></p> -->
<p class="room-date" style="<%= contentBoxExists ? 'display: none' : '' %>"><%=chatlist[i].date %></p>
</div>
- 1. 마지막 채팅을 불러오기 전에 contentBoxExists 를 false로 설정한다.
- 2. 마지막 채팅이 생성되면 contentBoxExists 를 true로 설정한다. (토글 키고 끄는 개념!!)
- 3. 채팅방 생성시간을 보여주는 요소의 style을 위와 같이 삼항연산자를 활용하여 true, false에 따라 다르게 보여지게 한다.
- 4. 완성!
'프로젝트 > SSR 게시판' 카테고리의 다른 글
[프로젝트] 게시판 | 트러블슈팅-Argument passed in must be a string of 12 bytes of 24 hex characters or an integer (1) | 2024.01.06 |
---|---|
[프로젝트] 게시판 | 5. 글 작성자만 수정, 삭제 버튼 보이게 만드는 법 (0) | 2024.01.06 |
[프로젝트] 게시판 | 4. 채팅 유저의 프로필 이미지 보여주기 & 프로필이 상대방 것인지 여부 체크하는 법 (1) | 2024.01.06 |
[프로젝트] 게시판 | 3. 채팅 목록 최신순 정렬하는 법 (2) | 2024.01.06 |
[프로젝트] 게시판 | 1. 채팅룸 생성여부에 따른 유저 이동 예외 처리 하는 법 (0) | 2024.01.06 |