-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathuser_server.service.dart
57 lines (45 loc) · 1.31 KB
/
user_server.service.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:safe/models/user/user.model.dart';
class UserServer {
final FirebaseFirestore _db;
static String path = "users";
UserServer(this._db);
// -> READ
Stream<User?> readFromId({required String id}) {
return _db.collection(path).doc(id).snapshots().map((doc) {
if (!doc.exists || doc.data() == null) {
return null;
} else {
return User.fromJson(doc.data()!);
}
});
}
Future<bool> userExists(String id) async {
try {
await readFromIdOnce(id: id);
return true;
} catch (e) {
return false;
}
}
Future<bool> userExistsFromPhone(String phone) async {
try {
var map =
await _db.collection(path).where("phone", isEqualTo: phone).get();
return map.docs.isNotEmpty;
} catch (e) {
return false;
}
}
Future<User?> readFromIdOnce({required String id}) async {
var map = await _db.collection(path).doc(id).get();
return map.exists ? User.fromJson(map.data()!) : null;
}
// -> UPSERT
Future<void> upsert(User user) {
var options = SetOptions(merge: true);
return _db.collection(path).doc(user.id).set(user.toMap(), options);
}
// -> DELETE
Future<void> delete(String id) => _db.collection(path).doc(id).delete();
}