Vue3, Firebase 프로젝트 - 채팅앱 VSignal

17. Vue3 Firebase 프로젝트 채팅앱 VSignal - 마지막 메시지 시간 표시 및 정렬

그랜파 개발자 2025. 3. 28. 05:19

마지막 메시지 시간 표시 및 정렬

채팅방 목록에서 마지막 메시지 시간 표시 및 정렬 기능을 추가하면,
채팅방 목록이 최신 메시지가 있는 순서대로 정렬되고, 마지막 메시지 시간이 보입니다.

1. Firestore에 마지막 메시지 시간 저장

메시지를 보낼 때 lastMessageAt 필드를 업데이트해야 해.

🔹 메시지 전송 함수 수정

import { updateDoc, doc, serverTimestamp } from "firebase/firestore";

const sendMessage = async (chatId, sender, message) => {
  const messageRef = doc(db, "chats", chatId);

  // 메시지 추가 & lastMessageAt 업데이트
  await updateDoc(messageRef, {
    messages: arrayUnion({
      sender,
      text: message,
      timestamp: serverTimestamp(),
    }),
    lastMessageAt: serverTimestamp(), // 마지막 메시지 시간 저장
  });
};

2. 채팅방 목록에서 마지막 메시지 시간 표시

Firestore에서 채팅방 목록을 가져올 때 lastMessageAt 기준으로 정렬하면 돼.

🔹 채팅방 목록 가져오기

import { collection, query, orderBy, onSnapshot } from "firebase/firestore";

const chatRooms = ref([]);

const fetchChatRooms = () => {
  const q = query(collection(db, "chats"), orderBy("lastMessageAt", "desc")); // 최신 메시지 순 정렬

  onSnapshot(q, (snapshot) => {
    chatRooms.value = snapshot.docs.map((doc) => ({
      id: doc.id,
      name: doc.data().name,
      lastMessageAt: doc.data().lastMessageAt?.toDate() || null,
    }));
  });
};

3. UI에서 마지막 메시지 시간 표시

🔹 ChatList.vue 예제

<template>
  <v-list>
    <v-list-item
      v-for="room in chatRooms"
      :key="room.id"
      @click="enterChat(room.id)"
    >
      <v-list-item-content>
        <v-list-item-title>{{ room.name }}</v-list-item-title>
        <v-list-item-subtitle>
          {{ formatTime(room.lastMessageAt) }}
        </v-list-item-subtitle>
      </v-list-item-content>
    </v-list-item>
  </v-list>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { fetchChatRooms } from "@/firebase";
import { format } from "date-fns";

const chatRooms = ref([]);

onMounted(() => {
  fetchChatRooms((rooms) => {
    chatRooms.value = rooms;
  });
});

const formatTime = (time) => {
  if (!time) return "메시지 없음";
  return format(time, "yyyy-MM-dd HH:mm");
};
</script>

✅ 최종 정리

1️⃣ 메시지 전송 시 lastMessageAt 업데이트
2️⃣ Firestore에서 lastMessageAt 기준 정렬
3️⃣ UI에서 lastMessageAt 표시

 

이제 채팅방 목록이 최신 메시지가 있는 순서대로 정렬되고, 마지막 메시지 시간이 보이게 될 거야! 🚀