-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTTPResponse.swift
More file actions
62 lines (52 loc) · 2.02 KB
/
HTTPResponse.swift
File metadata and controls
62 lines (52 loc) · 2.02 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//
// HTTPRespone.swift
// QuickHatchHTTP
//
// Created by Daniel Koster on 10/13/25.
//
import Foundation
public protocol HTTPResponse: Sendable {
var statusCode: HTTPStatusCode { get }
var headers: [String: String] { get }
var body: Data? { get }
}
public extension HTTPResponse {
func decode<T: Decodable>(decoder: JSONDecoder) throws -> Response<T> {
if let body = body {
let decodedBody = try decoder.decode(T.self, from: body)
return Response(data: decodedBody, statusCode: statusCode, headers: headers)
}
throw RequestError.noResponse
}
}
public struct QHHTTPResponse: HTTPResponse {
public let statusCode: HTTPStatusCode
public let headers: [String : String]
public let body: Data?
public init(body: Data?, urlResponse: URLResponse) {
self.body = body
self.headers = ((urlResponse as? HTTPURLResponse)?.allHeaderFields as? [String: String]) ?? [:]
self.statusCode = HTTPStatusCode(rawValue: (urlResponse as? HTTPURLResponse)?.statusCode ?? -1) ?? .serviceUnavailable
}
}
public struct Response<Value> {
public let data: Value
public let statusCode: HTTPStatusCode
public let headers: [AnyHashable: Any]
public init(data: Value,
statusCode: HTTPStatusCode,
headers: [AnyHashable: Any]) {
self.data = data
self.statusCode = statusCode
self.headers = headers
}
public func map<NewValue>(transform: (Value) -> NewValue) -> Response<NewValue> {
return Response<NewValue>(data: transform(data), statusCode: statusCode, headers: headers)
}
public func flatMap<NewValue> (transform: (Value) -> Response<NewValue>) -> Response<NewValue> {
return transform(data)
}
public func filter(query: (Value) -> Bool) -> Response<Value?> {
return query(data) ? Response<Value?>(data: data, statusCode: statusCode, headers: headers) : Response<Value?>(data: nil, statusCode: statusCode, headers: headers)
}
}