Created
June 23, 2017 22:42
-
-
Save ts95/b572e91890ba65d4f91172fdb042c913 to your computer and use it in GitHub Desktop.
Model protocol for Firebase/Database
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
import Foundation | |
import FirebaseDatabase | |
enum ModelError: Error { | |
case invalidProperties | |
} | |
protocol Model { | |
init?(snapshot: FIRDataSnapshot) | |
var id: String? { get set } | |
var serialized: [String : Any] { get } | |
mutating func store(at ref: FIRDatabaseReference) throws | |
func update(at ref: FIRDatabaseReference) throws | |
func delete(at ref: FIRDatabaseReference) | |
func validate() -> Bool | |
} | |
extension Model { | |
mutating func store(at ref: FIRDatabaseReference) throws { | |
guard validate() else { throw ModelError.invalidProperties } | |
let child = ref.childByAutoId() | |
child.updateChildValues(self.serialized) | |
self.id = child.key | |
} | |
func update(at ref: FIRDatabaseReference) throws { | |
guard validate() else { throw ModelError.invalidProperties } | |
ref.updateChildValues(self.serialized) | |
} | |
func delete(at ref: FIRDatabaseReference) { | |
ref.removeValue() | |
} | |
// MARK: - By default all models are considered valid. Should be overridden. | |
func validate() -> Bool { | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment