From 786267d0ebb337ad5b4f1e528fdd4c23731e0606 Mon Sep 17 00:00:00 2001 From: Iván Ávalos Date: Mon, 22 May 2023 00:09:43 -0600 Subject: Se implementa funcionalidad básica de chat MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/firebase/database.dart | 74 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 lib/firebase/database.dart (limited to 'lib/firebase/database.dart') 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 getUserById(String uid) async { + var snap = await _firestore.collection('users').doc(uid).get(); + return snap.data() != null ? FsUser.fromMap(snap.data()!) : null; + } + + Stream> getAllUsers() { + return _firestore.collection('users').snapshots().map>((e) { + return e.docs.map((e) { + return FsUser.fromMap(e.data()); + }).toList(); + }); + } + + Future 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> getGroupsByUserID(String uid) { + return _firestore + .collection('groups') + .where('members', arrayContains: uid) + .snapshots() + .map>((e) { + return e.docs.map((e) { + return Group.fromMap(e.data(), e.id); + }).toList(); + }); + } + + Stream> getMessagesByGroupId(String id) { + return _firestore + .collection('messages') + .doc(id) + .collection('messages') + .orderBy('sentAt') + .snapshots() + .map>((e) { + return e.docs.map((e) { + return Message.fromMap(e.data()); + }).toList(); + }); + } + + Future 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 saveGroup(Group group) async { + await _firestore.collection('groups').add(group.toMap()); + } +} -- cgit v1.2.3