Add Comment and get Comments done ✅
continuous-integration/drone/push Build is passing
Details
continuous-integration/drone/push Build is passing
Details
parent
0eb850e830
commit
c276e7ae1e
@ -0,0 +1,17 @@
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
|
||||
import '../../main.dart';
|
||||
import '../Comment.dart';
|
||||
import '../User.dart';
|
||||
|
||||
class CommentMapper {
|
||||
static Future<Comment> toModel(DocumentSnapshot<Map<String, dynamic>> snapshot) async {
|
||||
final data = snapshot.data();
|
||||
User? user = await MyApp.userViewModel.getUser(data?['user_id']);
|
||||
return Comment(
|
||||
snapshot.id,
|
||||
user!,
|
||||
data?["text"],
|
||||
data?["date"]);
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
|
||||
import '../main.dart';
|
||||
|
||||
class CommentService {
|
||||
createComment(String text, String idPost) async {
|
||||
var id = MyApp.userViewModel.userCurrent.id;
|
||||
final comment = <String, dynamic>{
|
||||
"user_id": id,
|
||||
"text": text,
|
||||
"date": DateTime.now(),
|
||||
"post_id": idPost
|
||||
};
|
||||
|
||||
await MyApp.db.collection("comments").add(comment);
|
||||
}
|
||||
|
||||
Future<List<QueryDocumentSnapshot<Map<String, dynamic>>>> getCommentsByPostId(
|
||||
String id) async {
|
||||
var response = await FirebaseFirestore.instance
|
||||
.collection("comments")
|
||||
.where("post_id", isEqualTo: id)
|
||||
.get();
|
||||
|
||||
return response.docs;
|
||||
}
|
||||
}
|
@ -1,8 +1,37 @@
|
||||
import 'package:justmusic/model/mapper/CommentMapper.dart';
|
||||
|
||||
import '../model/Comment.dart';
|
||||
import '../services/CommentService.dart';
|
||||
|
||||
class CommentViewModel {
|
||||
List<Comment> _comments = [];
|
||||
final CommentService _commentService = CommentService();
|
||||
|
||||
// Constructor
|
||||
CommentViewModel();
|
||||
|
||||
// Methods
|
||||
List<Comment> getCommentsPost(int idPost) {
|
||||
throw new Error();
|
||||
addComment(String text, String idPost) async {
|
||||
try {
|
||||
await _commentService.createComment(text,idPost);
|
||||
} catch(e) {
|
||||
print(e);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<Comment>> getCommentsByPostId(String id) async {
|
||||
try {
|
||||
var responseData = await _commentService.getCommentsByPostId(id);
|
||||
var commentsFutures = responseData.map((value) async {
|
||||
return await CommentMapper.toModel(value);
|
||||
}).toList();
|
||||
_comments = await Future.wait(commentsFutures);
|
||||
return _comments;
|
||||
} catch(e) {
|
||||
print(e);
|
||||
_comments = [];
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in new issue