diff options
author | Iván Ávalos <avalos@disroot.org> | 2023-05-22 00:09:43 -0600 |
---|---|---|
committer | Iván Ávalos <avalos@disroot.org> | 2023-05-22 00:09:43 -0600 |
commit | 786267d0ebb337ad5b4f1e528fdd4c23731e0606 (patch) | |
tree | 6e696aeae7fe14244b555da9815ecd19d0b92b14 /lib/firebase/database.dart | |
parent | 41b1ed94d6964e3fcedf427bbd323861b03fd1de (diff) | |
download | linkchat-786267d0ebb337ad5b4f1e528fdd4c23731e0606.tar.gz linkchat-786267d0ebb337ad5b4f1e528fdd4c23731e0606.tar.bz2 linkchat-786267d0ebb337ad5b4f1e528fdd4c23731e0606.zip |
Se implementa funcionalidad básica de chat
Diffstat (limited to 'lib/firebase/database.dart')
-rw-r--r-- | lib/firebase/database.dart | 74 |
1 files changed, 74 insertions, 0 deletions
diff --git a/lib/firebase/database.dart b/lib/firebase/database.dart new file mode 100644 index 0000000..eb9ef05 --- /dev/null +++ b/lib/firebase/database.dart @@ -0,0 +1,74 @@ +import 'dart:async'; + +import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:linkchat/models/group.dart'; +import 'package:linkchat/models/message.dart'; + +import '../models/user.dart'; + +class Database { + final FirebaseFirestore _firestore = FirebaseFirestore.instance; + + Future<FsUser?> getUserById(String uid) async { + var snap = await _firestore.collection('users').doc(uid).get(); + return snap.data() != null ? FsUser.fromMap(snap.data()!) : null; + } + + Stream<List<FsUser>> getAllUsers() { + return _firestore.collection('users').snapshots().map<List<FsUser>>((e) { + return e.docs.map((e) { + return FsUser.fromMap(e.data()); + }).toList(); + }); + } + + Future<void> saveUser(FsUser user) async { + await _firestore.collection('users').doc(user.uid).set({ + "uid": user.uid, + "displayName": user.displayName, + "photoUrl": user.photoUrl, + "email": user.email, + }); + } + + Stream<List<Group>> getGroupsByUserID(String uid) { + return _firestore + .collection('groups') + .where('members', arrayContains: uid) + .snapshots() + .map<List<Group>>((e) { + return e.docs.map((e) { + return Group.fromMap(e.data(), e.id); + }).toList(); + }); + } + + Stream<List<Message>> getMessagesByGroupId(String id) { + return _firestore + .collection('messages') + .doc(id) + .collection('messages') + .orderBy('sentAt') + .snapshots() + .map<List<Message>>((e) { + return e.docs.map((e) { + return Message.fromMap(e.data()); + }).toList(); + }); + } + + Future<void> saveMessage(Message msg, String groupId) async { + await _firestore + .collection('messages') + .doc(groupId) + .collection('messages') + .add(msg.toMap()); + await _firestore.collection('groups').doc(groupId).update({ + "recentMessage": msg.toMap(), + }); + } + + Future<void> saveGroup(Group group) async { + await _firestore.collection('groups').add(group.toMap()); + } +} |