Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add proper encoding for External Connect Accounts #269

Merged
merged 1 commit into from
Sep 1, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,24 @@ public struct ConnectAccountExternalAccountsList: Codable {
bankAccounts = try container.decodeIfPresent([BankAccount].self, forKey: .data)?.filter{ $0.object == "bank_account" }
}

public func encode(to encoder: any Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(object, forKey: .object)
try container.encodeIfPresent(hasMore, forKey: .hasMore)
try container.encodeIfPresent(url, forKey: .url)

// Merge cardAccounts and bankAccounts into a single array
var accounts: [AnyEncodable] = []
if let cardAccounts = cardAccounts {
accounts.append(contentsOf: cardAccounts.map { AnyEncodable($0) })
}
if let bankAccounts = bankAccounts {
accounts.append(contentsOf: bankAccounts.map { AnyEncodable($0) })
}

try container.encode(accounts, forKey: .data)
}

public init(object: String,
data: String? = nil,
hasMore: Bool? = nil,
Expand All @@ -48,4 +66,24 @@ public struct ConnectAccountExternalAccountsList: Codable {
self.cardAccounts = cardAccounts
self.bankAccounts = bankAccounts
}

enum CodingKeys: CodingKey {
case object
case data
case hasMore
case url
}

// A helper type to encode heterogeneous elements
struct AnyEncodable: Encodable {
private let _encode: (Encoder) throws -> Void

init<T: Encodable>(_ encodable: T) {
_encode = encodable.encode
}

func encode(to encoder: Encoder) throws {
try _encode(encoder)
}
}
}
Loading