Renamed import swift-openfoodfacts-sdk => OpenFoodFacts

This commit is contained in:
cdricms
2023-12-14 20:43:23 +01:00
parent 287561e2e6
commit 99460739b3
16 changed files with 8 additions and 25 deletions

View File

@@ -0,0 +1,36 @@
// The Swift Programming Language
// https://docs.swift.org/swift-book
import Foundation
public class OpenFoodFactsClient {
let version: Int = 0
public var prod: Bool = false
var baseURL: URL? {
if prod {
return URL(string: "https://world.openfoodfacts.org/api/v\(version)")
} else {
return URL(string: "https://world.openfoodfacts.net/api/v\(version)")
}
}
public init() {}
public func getProductByBarcode(_ barcode: String) async throws -> ProductResponse {
guard let endpoint = baseURL?.appendingPathComponent("product/\(barcode)") else { throw OFFError.invalidURL }
var request = URLRequest(url: endpoint)
request.setValue("application/json", forHTTPHeaderField: "accept")
let (data, response) = try await URLSession.shared.data(for: request)
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
throw OFFError.invalidResponse
}
do {
return try JSONDecoder().decode(ProductResponse.self, from: data)
}
}
}
enum OFFError: Error {
case invalidURL, invalidResponse
}