Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
implementation of firestore with clean
class RemoteDataSourceImpl : RemoteDataSource {
private val db = FirebaseFirestore.getInstance().apply {
this.firestoreSettings = FirebaseFirestoreSettings
.Builder()
.setPersistenceEnabled(true)
.build()
}
companion object {
const val DOCTORS_COLLECTION = "doctors"
const val PATIENTS_COLLECTION = "patients"
const val EVALUATIONS_COLLECTION = "evaluations"
const val EMAIL = "email"
}
override suspend fun saveDoctor(doctor: Doctor): Resource<String> =
suspendCancellableCoroutine { continuation ->
val newDocRef = db.collection(DOCTORS_COLLECTION).document()
db.collection(DOCTORS_COLLECTION)
.document(newDocRef.id)
.set(doctor.copy(id = newDocRef.id))
.addOnSuccessListener {
continuation.resume(Resource.Success(newDocRef.id))
}
.addOnFailureListener {
continuation.resume(Resource.ErrorException(it))
}
}
override suspend fun savePatients(doctorId: String, patient: Patient): Resource<Unit> =
suspendCancellableCoroutine { c ->
val newDocRef = db.collection(DOCTORS_COLLECTION).document()
db.collection(DOCTORS_COLLECTION)
.document(doctorId)
.collection(PATIENTS_COLLECTION)
.document(newDocRef.id)
.set(patient.copy(id = newDocRef.id))
.addOnSuccessListener {
c.resume(Resource.Success(Unit))
}
.addOnFailureListener {
c.resume(Resource.ErrorException(it))
}
}
override suspend fun getDoctor(doctorId: String): Resource<Doctor> =
suspendCancellableCoroutine { c ->
db.collection(DOCTORS_COLLECTION)
.document(doctorId)
.get()
.addOnSuccessListener {
c.resume(
Resource.Success(
it.toObject<Doctor>(Doctor::class.java)!!
)
)
}
.addOnFailureListener {
c.resume(Resource.ErrorException(it))
}
}
override suspend fun getPatients(doctorId: String): Resource<List<Patient>> =
suspendCancellableCoroutine { c ->
db.collection(DOCTORS_COLLECTION)
.document(doctorId)
.collection(PATIENTS_COLLECTION)
.get()
.addOnSuccessListener {
c.resume(
Resource.Success(
it.toObjects<Patient>(Patient::class.java)
)
)
}
.addOnFailureListener {
c.resume(Resource.ErrorException(it))
}
}
override suspend fun saveEvaluation(
doctorId: String,
patientId: String,
evaluation: Evaluation
): Resource<Unit> =
suspendCancellableCoroutine { c ->
db.collection(DOCTORS_COLLECTION)
.document(doctorId)
.collection(PATIENTS_COLLECTION)
.document(patientId)
.update(EVALUATIONS_COLLECTION, FieldValue.arrayUnion(evaluation))
.addOnSuccessListener {
c.resume(Resource.Success(Unit))
}
.addOnFailureListener {
c.resume(Resource.ErrorException(it))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment