From 450ca4880a2c5d85dbc35f4834f9f2af862e23d8 Mon Sep 17 00:00:00 2001 From: Dariusz Rybicki <dariusz@elixxir.io> Date: Sat, 12 Nov 2022 11:29:07 +0100 Subject: [PATCH] Add NotificationReport array coding helpers --- .../XXClient/Models/NotificationReport.swift | 10 +++++ .../Models/NotificationReportTests.swift | 39 +++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/Sources/XXClient/Models/NotificationReport.swift b/Sources/XXClient/Models/NotificationReport.swift index 06eb1d89..3a0192cc 100644 --- a/Sources/XXClient/Models/NotificationReport.swift +++ b/Sources/XXClient/Models/NotificationReport.swift @@ -45,3 +45,13 @@ extension NotificationReport: Codable { try JSONEncoder().encode(self) } } + +extension Array where Element == NotificationReport { + public static func decode(_ data: Data) throws -> Self { + try JSONDecoder().decode(Self.self, from: data) + } + + public func encode() throws -> Data { + try JSONEncoder().encode(self) + } +} diff --git a/Tests/XXClientTests/Models/NotificationReportTests.swift b/Tests/XXClientTests/Models/NotificationReportTests.swift index 9e99d825..4b8372fc 100644 --- a/Tests/XXClientTests/Models/NotificationReportTests.swift +++ b/Tests/XXClientTests/Models/NotificationReportTests.swift @@ -28,4 +28,43 @@ final class NotificationReportTests: XCTestCase { XCTAssertNoDifference(decodedModel, model) } + + func testCodingArray() throws { + let source1B64 = "dGVzdGVyMTIzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + let source2B64 = "ciI1cpyUUY/UPaVeMy1zBFWbZRgiZSXhY+cVoM+fCxwD" + let jsonString = """ + [ + { + "ForMe": true, + "Type": "\(NotificationReport.ReportType.default.rawValue)", + "Source": "\(source1B64)" + }, + { + "ForMe": false, + "Type": "\(NotificationReport.ReportType.request.rawValue)", + "Source": "\(source2B64)" + }, + ] + """ + let jsonData = jsonString.data(using: .utf8)! + let models = try [NotificationReport].decode(jsonData) + + XCTAssertNoDifference(models, [ + NotificationReport( + forMe: true, + type: .default, + source: Data(base64Encoded: source1B64)! + ), + NotificationReport( + forMe: false, + type: .request, + source: Data(base64Encoded: source2B64)! + ) + ]) + + let encodedModels = try models.encode() + let decodedModels = try [NotificationReport].decode(encodedModels) + + XCTAssertNoDifference(decodedModels, models) + } } -- GitLab