Skip to content

Instantly share code, notes, and snippets.

@molidev8
Created September 17, 2022 07:59
Show Gist options
  • Save molidev8/51d78e85c4fbfb5968531362ef76322c to your computer and use it in GitHub Desktop.
Save molidev8/51d78e85c4fbfb5968531362ef76322c to your computer and use it in GitHub Desktop.
Firebase Firestore
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