Skip to content

Instantly share code, notes, and snippets.

@ts95
Created June 23, 2017 22:42
Show Gist options
  • Save ts95/b572e91890ba65d4f91172fdb042c913 to your computer and use it in GitHub Desktop.
Save ts95/b572e91890ba65d4f91172fdb042c913 to your computer and use it in GitHub Desktop.
Model protocol for Firebase/Database
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