Skip to content

Commit

Permalink
added get function to DataCacheable
Browse files Browse the repository at this point in the history
  • Loading branch information
1amageek committed Jun 2, 2019
1 parent d0b4ea0 commit 3a0666b
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 42 deletions.
22 changes: 22 additions & 0 deletions Ballcap/DataCacheable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,25 @@ public extension DataCacheable where Self: Object {
}
}
}

public extension DataCacheable where Self: Object, Self: DataRepresentable {

func get(_ completion: @escaping (Self?, Error?) -> Void) {
if self.cache != nil {
self.data = self.cache
completion(self, nil)
} else {
Self.get(documentReference: self.documentReference, source: .cache) { (object, error) in
if let object: Self = object {
self.data = object.data
completion(object, error)
} else {
Self.get(documentReference: self.documentReference, source: .server) { (object, error) in
self.data = object?.data
completion(object, error)
}
}
}
}
}
}
23 changes: 0 additions & 23 deletions Ballcap/DataRepresentable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -241,26 +241,3 @@ public extension DataRepresentable where Self: Object {
return Disposer(.value(listenr))
}
}

// MARK: -

public extension DataRepresentable where Self: Object {

func on(_ completion: @escaping (Self?, Error?) -> Void) -> Self {
return self.on { (snapshot, error) in
if let error = error {
completion(nil, error)
return
}
guard let snapshot = snapshot, snapshot.exists else {
completion(nil, nil)
return
}
guard let document: Self = Self(snapshot: snapshot) else {
completion(nil, DocumentError.invalidData(snapshot.data()))
return
}
completion(document, nil)
}
}
}
19 changes: 0 additions & 19 deletions Ballcap/Object.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,25 +74,6 @@ open class Object: Documentable {
public func set(documentReference: DocumentReference) {
self.documentReference = documentReference
}

// MARK: -

private var _documentSnapshotBlocks: [FIRDocumentSnapshotBlock] = []

public func on(documentSnapshotBlock: @escaping FIRDocumentSnapshotBlock) -> Self {
self._documentSnapshotBlocks.append(documentSnapshotBlock)
return self
}

@discardableResult
public func get() -> Self {
self.documentReference.getDocument { (snapshot, error) in
self._documentSnapshotBlocks.forEach({ (block) in
block(snapshot, error)
})
}
return self
}
}

public extension DataRepresentable where Self: Object {
Expand Down

0 comments on commit 3a0666b

Please sign in to comment.