37 lines
1.1 KiB
Swift
37 lines
1.1 KiB
Swift
// 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
|
|
}
|