Last active
October 6, 2020 06:26
-
-
Save berkakkerman/39a12b36dacb362d3ae8f3cc2eec2471 to your computer and use it in GitHub Desktop.
Generic crud operations service for RxFirebaseFirestore
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
// | |
// 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