Renamed import swift-openfoodfacts-sdk => OpenFoodFacts
This commit is contained in:
36
Sources/OpenFoodFacts/OpenFoodFacts.swift
Normal file
36
Sources/OpenFoodFacts/OpenFoodFacts.swift
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user