-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTTPClient.swift
More file actions
27 lines (22 loc) · 828 Bytes
/
HTTPClient.swift
File metadata and controls
27 lines (22 loc) · 828 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import Foundation
public protocol URLSessioning {
func data(for request: URLRequest) async throws -> (Data, URLResponse)
}
extension URLSession: URLSessioning {}
public struct HTTPClient {
public enum HTTPError: Error { case badStatus(Int) }
private let session: URLSessioning
public init(session: URLSessioning = URLSession.shared) {
self.session = session
}
public func get(_ url: URL) async throws -> Data {
var req = URLRequest(url: url)
req.httpMethod = "GET"
let (data, resp) = try await session.data(for: req)
guard let http = resp as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
let status = (resp as? HTTPURLResponse)?.statusCode ?? -1
throw HTTPError.badStatus(status)
}
return data
}
}