From ee88c97446ba743c18c2660c32534cd1dba8153d Mon Sep 17 00:00:00 2001 From: emkartal1 Date: Wed, 16 Aug 2023 23:28:39 +0200 Subject: [PATCH] Add likes functions :white_check_mark: --- .../justMUSIC/lib/services/PostService.dart | 30 +++++++++++++++++++ .../lib/view_model/PostViewModel.dart | 18 +++++++++++ 2 files changed, 48 insertions(+) diff --git a/Sources/justMUSIC/lib/services/PostService.dart b/Sources/justMUSIC/lib/services/PostService.dart index a7d9742..f8a74db 100644 --- a/Sources/justMUSIC/lib/services/PostService.dart +++ b/Sources/justMUSIC/lib/services/PostService.dart @@ -128,4 +128,34 @@ class PostService { return recapList; } + + Future> getLikesByPostId(String id) async { + var response = await FirebaseFirestore.instance.collection("posts").doc(id).get(); + if (response.exists) { + var musicFavorite = response.get("likes"); + return List.from(musicFavorite); + } else { + return []; + } + } + + Future addOrDeleteFavoritePost(String id) async { + final idUser = MyApp.userViewModel.userCurrent.id; + var postRef = await FirebaseFirestore.instance + .collection("posts") + .doc(id); + var response = await postRef.get(); + + List likes = List.from(response.get("likes")); + + if (!likes.contains(idUser)) { + likes.add(idUser); + await postRef.update({"likes": likes}); + return false; + } else { + likes.remove(idUser); + await postRef.update({"likes": likes}); + return true; + } + } } diff --git a/Sources/justMUSIC/lib/view_model/PostViewModel.dart b/Sources/justMUSIC/lib/view_model/PostViewModel.dart index c70fbbb..b5d8545 100644 --- a/Sources/justMUSIC/lib/view_model/PostViewModel.dart +++ b/Sources/justMUSIC/lib/view_model/PostViewModel.dart @@ -98,4 +98,22 @@ class PostViewModel { rethrow; } } + + Future> getLikesByPostId(String id) async { + try { + return await _postService.getLikesByPostId(id); + } catch (e) { + print(e); + rethrow; + } + } + + Future addOrDeleteFavoritePost(String id) async { + try { + return await _postService.addOrDeleteFavoritePost(id); + } catch (e) { + print(e); + rethrow; + } + } }