From bdc4bb37f55799e0c02c85635501154820a663b2 Mon Sep 17 00:00:00 2001 From: cdricms <36056008+cdricms@users.noreply.github.com> Date: Sat, 6 Dec 2025 18:13:36 +0100 Subject: [PATCH] Ahhh, OpenFoodFacts and their types... --- .../KeyDecodingContainer+Helpers.swift | 11 +++++++++++ .../Schemas/NutriscoreData.swift | 19 +++++++++++++++++++ .../OpenFoodFactsTests.swift | 2 +- 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/Sources/OpenFoodFactsSDK/Extensions/KeyDecodingContainer+Helpers.swift b/Sources/OpenFoodFactsSDK/Extensions/KeyDecodingContainer+Helpers.swift index 0c83c9d..0dc5a67 100644 --- a/Sources/OpenFoodFactsSDK/Extensions/KeyDecodingContainer+Helpers.swift +++ b/Sources/OpenFoodFactsSDK/Extensions/KeyDecodingContainer+Helpers.swift @@ -8,4 +8,15 @@ extension KeyedDecodingContainer { } return nil } + + public func decodeStringOrInt(forKey key: Key) throws -> Int? { + if let intVal = try? decode(Int.self, forKey: key) { + return intVal + } + if let stringVal = try? decode(String.self, forKey: key) { + return Int(stringVal) + } + return nil + } + } diff --git a/Sources/OpenFoodFactsSDK/Schemas/NutriscoreData.swift b/Sources/OpenFoodFactsSDK/Schemas/NutriscoreData.swift index 4c40f16..e738e44 100644 --- a/Sources/OpenFoodFactsSDK/Schemas/NutriscoreData.swift +++ b/Sources/OpenFoodFactsSDK/Schemas/NutriscoreData.swift @@ -23,4 +23,23 @@ public struct NutriscoreData: Sendable, Codable { case energy } + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + saturatedFatRatio = try container.decodeIfPresent( + Float.self, forKey: .saturatedFatRatio) + saturatedFatRatioPoints = try container.decodeIfPresent( + Int.self, forKey: .saturatedFatRatioPoints) + saturatedFatRatioValue = try container.decodeIfPresent( + Float.self, forKey: .saturatedFatRatioValue) + + isBeverage = try container.decodeIfPresent( + Int.self, forKey: .isBeverage) + isCheese = try container.decodeIfPresent(Int.self, forKey: .isCheese) + isWater = try container.decodeStringOrInt(forKey: .isWater) + isFat = try container.decodeIfPresent(Int.self, forKey: .isFat) + energy = try container.decodeIfPresent(Int.self, forKey: .energy) + + } + } diff --git a/Tests/OpenFoodFactsTests/OpenFoodFactsTests.swift b/Tests/OpenFoodFactsTests/OpenFoodFactsTests.swift index d93d533..6347dd2 100644 --- a/Tests/OpenFoodFactsTests/OpenFoodFactsTests.swift +++ b/Tests/OpenFoodFactsTests/OpenFoodFactsTests.swift @@ -43,7 +43,7 @@ final class OpenFoodFactsTests: XCTestCase { let results = response.products let jsonResults = try JSONEncoder().encode(results) - try jsonResults.write(to: .init(filePath: "./jsonResults.json")) + _ = jsonResults XCTAssertFalse(results.isEmpty) XCTAssertEqual(results.count, 5)