From 79bdf9cac504d35cf3cf671232b28b5b5ac03f12 Mon Sep 17 00:00:00 2001 From: Iván Ávalos Date: Mon, 22 May 2023 23:06:18 -0600 Subject: Se implementan favoritos --- lib/firebase/database.dart | 63 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 60 insertions(+), 3 deletions(-) (limited to 'lib/firebase/database.dart') diff --git a/lib/firebase/database.dart b/lib/firebase/database.dart index 46970ce..3203748 100644 --- a/lib/firebase/database.dart +++ b/lib/firebase/database.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:cloud_firestore/cloud_firestore.dart'; +import 'package:linkchat/models/favorite.dart'; import 'package:linkchat/models/group.dart'; import 'package:linkchat/models/message.dart'; import 'package:simple_link_preview/simple_link_preview.dart'; @@ -10,6 +11,10 @@ import '../models/user.dart'; class Database { final FirebaseFirestore _firestore = FirebaseFirestore.instance; + // + // USERS + // + Future getUserById(String uid) async { var snap = await _firestore.collection('users').doc(uid).get(); return snap.data() != null ? FsUser.fromMap(snap.data()!) : null; @@ -32,6 +37,10 @@ class Database { }); } + // + // GROUPS + // + Stream> getGroupsByUserID(String uid) { return _firestore .collection('groups') @@ -44,6 +53,14 @@ class Database { }); } + Future saveGroup(Group group) async { + await _firestore.collection('groups').add(group.toMap()); + } + + // + // MESSAGES + // + Stream> getMessagesByGroupId(String id) { return _firestore .collection('messages') @@ -53,7 +70,7 @@ class Database { .snapshots() .map>((e) { return e.docs.map((e) { - return Message.fromMap(e.data()); + return Message.fromMap(e.data(), e.id); }).toList(); }); } @@ -70,7 +87,47 @@ class Database { }); } - Future saveGroup(Group group) async { - await _firestore.collection('groups').add(group.toMap()); + // + // FAVORITES + // + + Stream> getFavoritesByUserID(String uid) { + return _firestore + .collection('favorites') + .doc(uid) + .collection('favorites') + .orderBy('savedAt', descending: true) + .snapshots() + .map>( + (e) => e.docs.map((e) => Favorite.fromMap(e.data())).toList(), + ); + } + + Stream hasFavoriteForMessage(String userId, String? messageId) { + return _firestore + .collection('favorites') + .doc(userId) + .collection('favorites') + .where('messageId', isEqualTo: messageId) + .snapshots() + .map((e) => e.docs.isNotEmpty); + } + + Future saveFavorite(Favorite favorite, String userId) { + return _firestore + .collection('favorites') + .doc(userId) + .collection('favorites') + .add(favorite.toMap()); + } + + Future removeFavorite(String userId, String? messageId) async { + CollectionReference reference = + _firestore.collection('favorites').doc(userId).collection('favorites'); + var favorites = + await reference.where('messageId', isEqualTo: messageId).get(); + for (var e in favorites.docs) { + reference.doc(e.id).delete(); + } } } -- cgit v1.2.3