Skip to content

Commit

Permalink
Use a container type for encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
Supereg committed Nov 18, 2023
1 parent 3916d30 commit 971005f
Showing 1 changed file with 19 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,17 @@

import FirebaseFirestore
import SpeziAccount
import OSLog


private struct SingleKeyContainer<Value: Codable>: Codable {
let value: Value
}


class FirestoreEncodeVisitor: AccountValueVisitor {
private let logger = Logger(subsystem: "edu.stanford.spezi.firebase", category: "FirestoreEncode")

typealias Data = [String: Any]

private var values: Data = [:]
Expand All @@ -21,9 +29,19 @@ class FirestoreEncodeVisitor: AccountValueVisitor {

func visit<Key: AccountKey>(_ key: Key.Type, _ value: Key.Value) {
let encoder = Firestore.Encoder()

// the firestore encode method expects a container type!
let container = SingleKeyContainer(value: value)

do {
values["\(Key.self)"] = try encoder.encode(value)
let result = try encoder.encode(container)
guard let encoded = result["value"] else {
preconditionFailure("Layout of SingleKeyContainer changed. Does not contain value anymore: \(result)")
}

values["\(Key.self)"] = encoded
} catch {
logger.error("Failed to encode \("\(value)") for key \(key): \(error)")
errors["\(Key.self)"] = error
}
}
Expand Down

0 comments on commit 971005f

Please sign in to comment.