Skip to content

Instantly share code, notes, and snippets.

@berkakkerman
Last active October 6, 2020 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berkakkerman/39a12b36dacb362d3ae8f3cc2eec2471 to your computer and use it in GitHub Desktop.
Save berkakkerman/39a12b36dacb362d3ae8f3cc2eec2471 to your computer and use it in GitHub Desktop.
Generic crud operations service for RxFirebaseFirestore
//
// FirestoreService.swift
// Valido-iOS
//
// Created by Berk Akkerman on 25.06.2020.
// Copyright © 2020 Ecospend. All rights reserved.
//
import Foundation
import RxSwift
import FirebaseFirestore
import RxFirebaseFirestore
class FirestoreService<T: Codable> {
var collection: FirestoreCollection
var collectionReference: CollectionReference
init(collection: FirestoreCollection) {
self.collection = collection
self.collectionReference = Firestore.firestore().collection(collection.name)
}
func getAll() -> Observable<[T]> {
return collectionReference
.rx
.getDocuments()
.map { $0.documents.compactMap { $0.data().toCodable(type: T.self) } }
}
func get(id: String) -> Observable<T?> {
return collectionReference
.document(id)
.rx
.getDocument()
.map { ($0.data()?.toCodable(type: T.self)) }
}
func add(item: T) -> Observable<DocumentReference> {
if let itemToAdd = item.dictionary {
return collectionReference
.rx
.addDocument(data: itemToAdd)
}
return Observable.from(optional: nil)
}
func update(id: String, item: T) -> Observable<Void> {
if let updateItem = item.dictionary {
return collectionReference
.document(id)
.rx
.updateData(updateItem)
}
return Observable<Any>.from(optional: nil).mapToVoid()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment