Created
September 17, 2022 07:59
-
-
Save molidev8/51d78e85c4fbfb5968531362ef76322c to your computer and use it in GitHub Desktop.
Firebase Firestore
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
private val auth: FirebaseAuth = FirebaseAuth.getInstance() | |
suspend fun getUser(): User? { | |
var user: UserFromFirebase? | |
try { | |
val documentSnapshot = db.collection(USERS).document(auth.uid).get().await() | |
user = documentSnapshot.toObject() | |
Log.d(FIRESTORE, "DocumentSnapshot data: ${documentSnapshot.data}") | |
} catch (e: Exception) { | |
user = null | |
Log.d(FIRESTORE, "get failed with ", e) | |
} | |
return user?.toUser() | |
} | |
suspend fun setUser(user: User) { | |
db.collection(USERS).document(auth.uid).set(user, SetOptions.merge()) | |
.addOnCompleteListener { task -> | |
if (task.isSuccessful) | |
Log.d(FIRESTORE, "user saved successfully") | |
else if(task.isCanceled) | |
Log.d(FIRESTORE, "save user failed ", task.exception) | |
} | |
} | |
suspend fun saveFavRecipe(id: Int) { | |
db.collection(USERS).document(auth.uid).update("savedRecipes", FieldValue.arrayUnion(id)) | |
.addOnCompleteListener { task -> | |
if (task.isSuccessful) | |
Log.d(FIRESTORE, "fav recipe added") | |
else if(task.isCanceled) | |
Log.d(FIRESTORE, "fav recipe failed ", task.exception) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment