지난 편에 이어서 구조를 짜자면
유저가 작성자에게 contact하면 먼저 채팅방이 생성되어있는지 확인합니다.
기존 채팅방이 존재할 시 기존의 채팅방으로 이동하며, 존재하지 않을 시 첫 메세지 전송시 새로운 채팅방을 생성합니다
채팅방의 ID는 작성자+유저ID로 구성되어있기 때문에 기존 채팅방이 존재하면 새로 생성되지 않습니다
(firestore에는 채팅룸 데이터와 개인의 채팅룸의 데이터가 있습니다)
이런 너낌스 유저마다 자신의 포함된 채팅Id 데이터를 갖고 있습니다
onButtonPressed(String chatroomId) async {
final chatList = await ChatService().getChatList(); // 유저가 갖고 있는 모든 채팅방의 정보를 가지고 오는 메소드
bool isExist = chatList
.map(
(e) => e.chatRoomId,
)
.toList()
.contains(chatroomId);
if (isExist) {
//기존 채팅방으로 이동
} else {
//새로운 채팅방으로 이동
}
}
Future<List<String>> getChatList() async {
try {
final snapshot =
await _firestore.collection('users').doc(userEmail).get();
if (snapshot.exists) {
final List<String> chats = [];
(snapshot.data() as Map)
.entries
.map((e) => chats.add(e))
.toList();
return chats;
} else {
return [];
}
} catch (e) {
throw e;
}
}
Stream<ChatRoom> getChatRoomData(String chatroomId) {
try {
final stream = _firestore
.collection('chatrooms')
.doc(chatroomId)
.snapshots()
.map((event) => ChatRoom.fromDocumentSnapshot(event));
return stream;
} catch (e) {
throw e;
}
}
stream을 사용하는 부분입니다
Future newChatRoom(ChatRoom chatroom, Message message) async {
_firestore
.collection('chatrooms')
.doc(chatroom.chatRoomId)
.set(chatroom.toJson());
}
void sendMessage(String chatRoomId, Message message) async {
try {
final snapshot =
await _firestore.collection('chatrooms').doc(chatRoomId).get();
if (snapshot.exists) {
final roomData = ChatRoom.fromDocumentSnapshot(snapshot);
final messages = roomData.messages;
messages.add(message);
_firestore
.collection('chatrooms')
.doc(chatRoomId)
.update({'messages': messages.map((e) => e.toJson()).toList()});
}
} catch (e) {
print(e);
}
}
해당 코드 깃링크
https://github.com/PoomAt-E/hobby-mate
https://github.com/2023-GSC-Diviction/Diviction-User