Created
May 19, 2020 09:17
-
-
Save Laebrye/1b24e23086472761ada6afd2a908b3cd to your computer and use it in GitHub Desktop.
A FirestoreService class - heavily influenced by Andrea Bizzotto's excellent courses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:cloud_firestore/cloud_firestore.dart'; | |
import 'package:flutter/foundation.dart'; | |
import 'package:rxdart/rxdart.dart'; | |
class FirestoreService { | |
FirestoreService._(); | |
static final instance = FirestoreService._(); | |
CollectionReference collectionReference(String path) { | |
return Firestore.instance.collection(path); | |
} | |
Future<String> addData({ | |
@required String collectionPath, | |
@required Map<String, dynamic> data, | |
}) async { | |
final reference = Firestore.instance.collection(collectionPath); | |
final docReference = await reference.add(data); | |
return docReference.documentID; | |
} | |
Future<void> setData({ | |
@required String path, | |
@required Map<String, dynamic> data, | |
bool merge = false, | |
}) async { | |
final reference = Firestore.instance.document(path); | |
await reference.setData(data, merge: merge); | |
} | |
Future<void> deleteData({@required String path}) async { | |
final reference = Firestore.instance.document(path); | |
await reference.delete(); | |
} | |
Stream<List<T>> collectionStream<T>({ | |
@required String path, | |
@required T builder(Map<String, dynamic> data, String documentID), | |
Query queryBuilder(Query query), | |
int sort( | |
T lhs, | |
T rhs, | |
), | |
}) { | |
Query query = Firestore.instance.collection(path); | |
if (queryBuilder != null) { | |
query = queryBuilder(query); | |
} | |
final Stream<QuerySnapshot> snapshots = query.snapshots(); | |
return snapshots.map((snapshot) { | |
final result = snapshot.documents | |
.map((snapshot) => builder(snapshot.data, snapshot.documentID)) | |
.where((value) => value != null) | |
.toList(); | |
if (sort != null) { | |
result.sort(sort); | |
} | |
return result; | |
}).shareValue(); | |
} | |
Stream<T> documentStream<T>({ | |
@required String path, | |
@required T builder(Map<String, dynamic> data, String documentID), | |
}) { | |
final DocumentReference reference = Firestore.instance.document(path); | |
final Stream<DocumentSnapshot> snapshots = reference.snapshots(); | |
return snapshots | |
.map((snapshot) => builder(snapshot.data, snapshot.documentID)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment