Untitled
unknown
plain_text
5 years ago
2.7 kB
9
Indexable
class FirestoreUserDao {
CollectionReference _users;
FirestoreUserDao(String usersPath) {
_users = Firestore.instance.collection(usersPath);
}
Future<String> createUser() async {
var ref = _users.document();
await ref.setData({'userId': ref.documentID});
var sharedPrefs = await SharedPreferences.getInstance();
await sharedPrefs.setString('userId', ref.documentID);
return ref.documentID;
}
Future<String> getUserId() async {
var sharedPrefs = await SharedPreferences.getInstance();
return Future.value(sharedPrefs.get('userId'));
}
Future<void> setName(String name) {
return getUserId()
.then((userId) => _users.document(userId).updateData({'name': name}));
}
Stream<String> observeId() async* {
yield* _users
.document(await getUserId())
.snapshots()
.map((snapshot) => snapshot.data['userId'] as String);
}
Stream<String> observeThisUserName() async* {
yield* observeName(await getUserId());
}
Stream<String> observeName(String userId) async* {
yield* _users
.document(userId)
.snapshots()
.map((snapshot) => snapshot.data['name'] as String);
}
Future<String> getName(String userId) {
return observeName(userId).first;
}
Future<void> addProject(String projectId) async {
return addProjectToUser(await getUserId(), projectId);
}
Future<bool> addProjectToUser(String userId, String projectId) async {
return _users
.document(userId)
.collection('projects')
.document(projectId)
.setData({})
.then((_) => Future.value(true))
.catchError((error) => print('ERROR $error'));
}
Stream<List<String>> observeProjects() async* {
yield* _users
.document(await getUserId())
.collection('projects')
.snapshots()
.map((snapshot) => snapshot.documents)
.map((documents) =>
documents.map((document) => document.documentID).toList());
}
Future<int> getProjectsCount() async {
return _users
.document(await getUserId())
.collection('projects')
.getDocuments()
.then((documents) => documents.documents.length);
}
// todo refactor this code
Future<String> getUserIdFromUserCode(String userCode) async {
QuerySnapshot documents = await _users
.where('userId', isGreaterThanOrEqualTo: userCode)
.getDocuments();
String properUserId;
documents.documents.forEach((document) {
String userId = (document.data['userId'] as String);
if (userId.startsWith(userCode) && userCode.length == 4)
properUserId = userId;
});
return Future.value(properUserId);
}
}
Editor is loading...