๋ฉ์ธ์ง๋ฅผ ์ฃผ๊ณ ๋ฐ์ผ๋ ค๋ฉด ์ผ๋จ ๋ฉ์ธ์ง๋ฅผ ๊ตฌ๋ณํ ๊ณ ์ ํ id๊ฐ์ด ํ์ํ๋ค. ๊ทธ๋ฆฌ๊ณ ์์ฑ์๊ฐ์ด ํ์ํ ๊ฒ์ด๋ค. ๊ทธ๋ฆฌ๊ณ ๋ณด๋ธ ์ฌ๋๊ณผ ๋ฐ๋ ์ฌ๋์ ์ ์ ์์ด์ผ ํ๊ณ , ๋ฐ๋ ์ฌ๋์ด ์ฝ์๋์ง ์ฌ๋ถ์ ์ค์ ๋ฉ์ธ์ง ํ ์คํธ๊ฐ ํ์ํ ๊ฒ์ด๋ค. ์นดํก์ ๋ณด๋ฉด ์ด๋ค ์ ๋ณด๋ค์ด ํ์ํ ์ง ๋ฐ๋ก ์ ์ ์๋ค!
MVVM ํจํด์ ๋ฐ๋ผ ์ฝ๋๋ฅผ ์์ฑํ์๋ค. ๋ฉ์ธ์ง ๋ชจ๋ธ์ ์์ฑํ๋ค. ํ์ด์ด๋ฒ ์ด์ค์์ ์ ๊ณตํ๋ @DocumentID์ Timestamp๋ฅผ ์ด์ฉํด id์ timestamp๋ฅผ ์ ์ํ๋ค. fromId๋ ๋ฉ์ธ์ง๋ฅผ ๋ณด๋ด๋ ์ฌ๋์ id์ด๊ณ , toId๋ ๋ฉ์ธ์ง๋ฅผ ๋ฐ๋ ์ฌ๋์ id์ด๋ค. ๊ทธ๋ฆฌ๊ณ read๋ ๋ฉ์ธ์ง๋ฅผ ์ฝ์๋์ง ์ฌ๋ถ๋ฅผ ๋ํ๋ด๋ Boolํ์ ์ด๊ณ text๋ ๋ฉ์ธ์ง ํ ์คํธ์ด๋ค.
import FirebaseFirestoreSwift
import Firebase
struct Message: Identifiable, Decodable {
@DocumentID var id: String?
let timestamp: Timestamp
let fromId: String
let toId: String
let read: Bool
let text: String
}
ํ์ด์ด๋ฒ ์ด์ค ํ์ด์ด์คํ ์ด์์ messages ์ปฌ๋ ์ ์ ์๋์ ๊ฒฝ๋ก๋ก ๋ฉ์ธ์ง๋ฅผ ์ ์ฅ์ ํ ๊ณํ์ด๋ค. ๋ฐ๋ ์ฌ๋ ํด๋์ ๋ณด๋ธ ์ฌ๋ ํด๋์, ์ด ๋๋ฒ ์ ์ฅํด์ผ ํ๋ค.
๋ฉ์ธ์ง ์ปฌ๋ ์ ๊ฒฝ๋ก๋ ์ฝ๋๋ฅผ ์์ฑํ๋ฉด์ ์ค๋ณต๋๋ฏ๋ก Constants ํ์ผ์ ์ ์ฅํ์๋ค.
let COLLECTION_MESSAGES = Firestore.firestore().collection("messages")
๋ฉ์ธ์ง๋ฅผ ๋ณด๋ด๋ ํจ์์์ ๋จผ์ ๋ฌธ์์ ๊ฒฝ๋ก๋ฅผ ์ ์ํ๋ค. currentUserId๋ ํ์ฌ ์ ์ ์ id์ด๊ณ , chatPartnerId๋ ์ฑํ ์๋์ id์ด๋ค. ๊ฒฝ๋ก๋ฅผ ์ ์ํ๋ค. chatPartnerId์ .document()๋ฅผ ์ถ๊ฐํด ๋ฌธ์๋ฅผ ์์ฑํ์ง ์์ ์ด์ ๋, currentUserRef์ ์ ์ฅ๋๋ ๋ฌธ์์ id๊ฐ๊ณผ ๋์ผํ๊ฒ ํ๊ธฐ ์ํด์์ด๋ค.
let currentUserRef = COLLECTION_MESSAGES.document(currentUserId).collection(chatPartnerId).document()
let chatPartnerRef = COLLECTION_MESSAGES.document(chatPartnerId).collection(currentUserId)
์ต์ข ๊ฒฝ๋ก์ ๋ฐ์ดํฐ๋ฅผ ๋ฃ์ผ๋ ค๋ฉด, ํ์ด์ด๋ฒ ์ด์ค์ setData() ํจ์๋ฅผ ์ฌ์ฉํด์ผ ํ๋ค. ์ด ํจ์๋ ๋ฐ์ดํฐ๋ฅผ ๋ฐ๋๋ฐ, ๋ฐ์ดํฐ์ ํ์ ์ [String: Any]์ฌ์ผ ํ๋ค. messageId์ currentUserRef์ ๋ฌธ์ id๊ฐ์ด๋ค. chatPartnerRef์ currentUserRef์ ๋ฌธ์ id๊ฐ์ด ๋์ผํ๊ฒ ๋ฌธ์๋ฅผ ์์ฑํ ์ดํ์ ๋ฐ์ดํฐ๋ฅผ ๋ฃ๋๋ค.
let data: [String: Any] = ["timestamp": Timestamp(date: Date()),
"fromId": currentUserId,
"toId": chatPartnerId,
"read": false,
"text": messageText]
let messageId = currentUserRef.documentID
currentUserRef.setData(data)
chatPartnerRef.document(messageId).setData(data)