import Foundation
import FirebaseFirestore
class ChatViewModel: ObservableObject {
@Published var chat: ChatModel
@Published var opposingUser: User
init(oppUser: User) {
self.opposingUser = oppUser
Task {
if let fetchedChat = try? await fetchChat(oppUser: oppUser) {
self.chat = fetchedChat
}
}
}
init(chat: ChatModel) {
self.chat = chat
Task {
if let fetchedUser = try? await getOpposingUser(chat: chat) {
self.opposingUser = fetchedUser
}
}
}
@MainActor
func fetchChat(oppUser: User) async throws -> ChatModel? {
do {
let documents = try await Firestore.firestore()
.collection("conversations")
.whereField("users", arrayContains: UserService.shared.currentUser?.id ?? "error")
.whereField("users", arrayContains: oppUser.id)
.getDocuments()
for document in documents.documents {
guard let chatData = try? document.data(as: ChatModel.self) else {
print("[DEBUG fetchChat(oppUser: User)]: Error while converting Firebase Document to ChatModel ")
return nil
}
return chatData
}
} catch {
print("[DEBUG fetchChat(oppUser: User)]: \(error)")
throw error // Re-throw the error so it can be handled by the caller if needed
}
return nil
}
@MainActor
func getOpposingUser(chat: ChatModel) async throws -> User? {
do {
let opposingUid: String
if chat.users[0] == UserService.shared.currentUser?.id {
opposingUid = chat.users[1]
} else {
opposingUid = chat.users[0]
}
let document = try await Firestore
.firestore()
.collection("users")
.document(opposingUid)
.getDocument()
guard let opposingUserDoc = try? document.data(as: User.self) else {
// Handle the case where conversion to User fails
print("[DEBUG (getOpposingUser(chat: chatModel)]: Error while converting Firebase-Document to User ")
return nil
}
return opposingUserDoc
} catch {
print("[DEBUG (getOpposingUser(chat: chatModel)]: \(error) ")
throw error
}
return nil
}
}
I tried to "pre initilize" the variables with something like self.chat = ChatModel() but due to the nature of my Cahtmodel I can't init it without properties.
0 comments:
Post a Comment
Thanks