Store feed.authors in ODB. Make Author Codable.

This commit is contained in:
Brent Simmons 2018-09-15 11:16:05 -07:00
parent 904feb9950
commit 0f59b904ef
2 changed files with 46 additions and 9 deletions

View File

@ -66,7 +66,22 @@ public final class Feed: DisplayNameProvider, UnreadCountProvider, Hashable {
}
public var name: String?
public var authors: Set<Author>?
public var authors: Set<Author>? {
get {
guard let authorsJSON = settingsTable.string(for: Key.authors) else {
return nil
}
return Author.authorsWithJSON(authorsJSON)
}
set {
if let authorsJSON = newValue?.json() {
settingsTable.setString(authorsJSON, for: Key.authors)
}
else {
settingsTable.setString(nil, for: Key.authors)
}
}
}
public var editedName: String? {
didSet {
@ -148,10 +163,6 @@ public final class Feed: DisplayNameProvider, UnreadCountProvider, Hashable {
self.init(account: account, url: url, feedID: feedID)
self.name = dictionary[Key.name] as? String
self.editedName = dictionary[Key.editedName] as? String
if let authorsDiskArray = dictionary[Key.authors] as? [[String: Any]] {
self.authors = Author.authorsWithDiskArray(authorsDiskArray)
}
}
public static func isFeedDictionary(_ d: [String: Any]) -> Bool {
@ -175,9 +186,6 @@ public final class Feed: DisplayNameProvider, UnreadCountProvider, Hashable {
if let editedName = editedName {
d[Key.editedName] = editedName
}
if let authorsArray = authors?.diskArray() {
d[Key.authors] = authorsArray
}
return d
}

View File

@ -8,7 +8,7 @@
import Foundation
public struct Author: Hashable {
public struct Author: Codable, Hashable {
public let authorID: String // calculated
public let name: String?
@ -73,6 +73,23 @@ public struct Author: Hashable {
return d
}
public static func authorsWithJSON(_ jsonString: String) -> Set<Author>? {
// This is JSON stored in the database, not the JSON Feed version of an author.
guard let data = jsonString.data(using: .utf8) else {
return nil
}
let decoder = JSONDecoder()
do {
let authors = try decoder.decode([Author].self, from: data)
return Set(authors)
}
catch {
assertionFailure("JSON representation of Author array could not be decoded: \(jsonString) error: \(error)")
}
return nil
}
public static func authorsWithDiskArray(_ diskArray: [[String: Any]]) -> Set<Author>? {
let authors = diskArray.compactMap { Author(dictionary: $0) }
@ -89,4 +106,16 @@ extension Set where Element == Author {
}
return self.map{ $0.dictionary }
}
public func json() -> String? {
let encoder = JSONEncoder()
do {
let jsonData = try encoder.encode(Array(self))
return String(data: jsonData, encoding: .utf8)
}
catch {
assertionFailure("JSON representation of Author array could not be encoded: \(self) error: \(error)")
}
return nil
}
}