storeChatIfNot method
- ChatModel chat
Stores the given chat if it does not exist already.
chat
: The chat to be stored.
Implementation
@override
Future<ChatModel> storeChatIfNot(ChatModel chat) async {
if (chat.id == null) {
var currentUser = await _userService.getCurrentUser();
if (chat is PersonalChatModel) {
if (currentUser?.id == null || chat.user.id == null) {
return chat;
}
var userIds = <String>[
currentUser!.id!,
chat.user.id!,
];
var reference = await _db
.collection(_options.chatsMetaDataCollectionName)
.withConverter(
fromFirestore: (snapshot, _) =>
FirebaseChatDocument.fromJson(snapshot.data()!, snapshot.id),
toFirestore: (chat, _) => chat.toJson(),
)
.add(
FirebaseChatDocument(
personal: true,
canBeDeleted: chat.canBeDeleted,
users: userIds,
lastUsed: Timestamp.now(),
),
);
for (var userId in userIds) {
await _db
.collection(_options.usersCollectionName)
.doc(userId)
.collection(_options.userChatsCollectionName)
.doc(reference.id)
.set({'users': userIds}, SetOptions(merge: true));
}
chat.id = reference.id;
} else if (chat is GroupChatModel) {
if (currentUser?.id == null) {
return chat;
}
var userIds = <String>[
currentUser!.id!,
...chat.users.map((e) => e.id!),
];
var reference = await _db
.collection(_options.chatsMetaDataCollectionName)
.withConverter(
fromFirestore: (snapshot, _) =>
FirebaseChatDocument.fromJson(snapshot.data()!, snapshot.id),
toFirestore: (chat, _) => chat.toJson(),
)
.add(
FirebaseChatDocument(
personal: false,
title: chat.title,
imageUrl: chat.imageUrl,
canBeDeleted: chat.canBeDeleted,
users: userIds,
lastUsed: Timestamp.now(),
),
);
for (var userId in userIds) {
await _db
.collection(_options.usersCollectionName)
.doc(userId)
.collection(_options.groupChatsCollectionName)
.doc(reference.id)
.set({'users': userIds}, SetOptions(merge: true));
}
chat.id = reference.id;
} else {
throw Exception('Chat type not supported for firebase');
}
}
return chat;
}