|
| 1 | +import Foundation |
| 2 | + |
| 3 | +public struct Client { |
| 4 | + public let url: URL |
| 5 | + public var token: String? |
| 6 | + |
| 7 | + public init(url: URL, token: String? = nil) { |
| 8 | + self.url = url |
| 9 | + self.token = token |
| 10 | + } |
| 11 | + |
| 12 | + static let decoder: JSONDecoder = { |
| 13 | + var dec = JSONDecoder() |
| 14 | + dec.dateDecodingStrategy = .iso8601withOptionalFractionalSeconds |
| 15 | + return dec |
| 16 | + }() |
| 17 | + |
| 18 | + static let encoder: JSONEncoder = { |
| 19 | + var enc = JSONEncoder() |
| 20 | + enc.dateEncodingStrategy = .iso8601withFractionalSeconds |
| 21 | + return enc |
| 22 | + }() |
| 23 | + |
| 24 | + func request<T: Encodable & Sendable>( |
| 25 | + _ path: String, |
| 26 | + method: HTTPMethod, |
| 27 | + body: T? = nil |
| 28 | + ) async throws(ClientError) -> HTTPResponse { |
| 29 | + let url = self.url.appendingPathComponent(path) |
| 30 | + var req = URLRequest(url: url) |
| 31 | + if let token { req.addValue(token, forHTTPHeaderField: Headers.sessionToken) } |
| 32 | + req.httpMethod = method.rawValue |
| 33 | + do { |
| 34 | + if let body { req.httpBody = try Client.encoder.encode(body) } |
| 35 | + } catch { |
| 36 | + throw .encodeFailure |
| 37 | + } |
| 38 | + let data: Data |
| 39 | + let resp: URLResponse |
| 40 | + do { |
| 41 | + (data, resp) = try await URLSession.shared.data(for: req) |
| 42 | + } catch { |
| 43 | + throw .network(error) |
| 44 | + } |
| 45 | + guard let httpResponse = resp as? HTTPURLResponse else { |
| 46 | + throw .unexpectedResponse(data) |
| 47 | + } |
| 48 | + return HTTPResponse(resp: httpResponse, data: data, req: req) |
| 49 | + } |
| 50 | + |
| 51 | + func request( |
| 52 | + _ path: String, |
| 53 | + method: HTTPMethod |
| 54 | + ) async throws(ClientError) -> HTTPResponse { |
| 55 | + let url = self.url.appendingPathComponent(path) |
| 56 | + var req = URLRequest(url: url) |
| 57 | + if let token { req.addValue(token, forHTTPHeaderField: Headers.sessionToken) } |
| 58 | + req.httpMethod = method.rawValue |
| 59 | + let data: Data |
| 60 | + let resp: URLResponse |
| 61 | + do { |
| 62 | + (data, resp) = try await URLSession.shared.data(for: req) |
| 63 | + } catch { |
| 64 | + throw .network(error) |
| 65 | + } |
| 66 | + guard let httpResponse = resp as? HTTPURLResponse else { |
| 67 | + throw .unexpectedResponse(data) |
| 68 | + } |
| 69 | + return HTTPResponse(resp: httpResponse, data: data, req: req) |
| 70 | + } |
| 71 | + |
| 72 | + func responseAsError(_ resp: HTTPResponse) -> ClientError { |
| 73 | + do { |
| 74 | + let body = try Client.decoder.decode(Response.self, from: resp.data) |
| 75 | + let out = APIError( |
| 76 | + response: body, |
| 77 | + statusCode: resp.resp.statusCode, |
| 78 | + method: resp.req.httpMethod!, |
| 79 | + url: resp.req.url! |
| 80 | + ) |
| 81 | + return .api(out) |
| 82 | + } catch { |
| 83 | + return .unexpectedResponse(resp.data.prefix(1024)) |
| 84 | + } |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +public struct APIError: Decodable { |
| 89 | + let response: Response |
| 90 | + let statusCode: Int |
| 91 | + let method: String |
| 92 | + let url: URL |
| 93 | + |
| 94 | + var description: String { |
| 95 | + var components = ["\(method) \(url.absoluteString)\nUnexpected status code \(statusCode):\n\(response.message)"] |
| 96 | + if let detail = response.detail { |
| 97 | + components.append("\tError: \(detail)") |
| 98 | + } |
| 99 | + if let validations = response.validations, !validations.isEmpty { |
| 100 | + let validationMessages = validations.map { "\t\($0.field): \($0.detail)" } |
| 101 | + components.append(contentsOf: validationMessages) |
| 102 | + } |
| 103 | + return components.joined(separator: "\n") |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +public struct Response: Decodable { |
| 108 | + let message: String |
| 109 | + let detail: String? |
| 110 | + let validations: [FieldValidation]? |
| 111 | +} |
| 112 | + |
| 113 | +public struct FieldValidation: Decodable { |
| 114 | + let field: String |
| 115 | + let detail: String |
| 116 | +} |
| 117 | + |
| 118 | +public enum ClientError: Error { |
| 119 | + case api(APIError) |
| 120 | + case network(any Error) |
| 121 | + case unexpectedResponse(Data) |
| 122 | + case encodeFailure |
| 123 | + |
| 124 | + public var description: String { |
| 125 | + switch self { |
| 126 | + case let .api(error): |
| 127 | + return error.description |
| 128 | + case let .network(error): |
| 129 | + return error.localizedDescription |
| 130 | + case let .unexpectedResponse(data): |
| 131 | + return "Unexpected or non HTTP response: \(data)" |
| 132 | + case .encodeFailure: |
| 133 | + return "Failed to encode body" |
| 134 | + } |
| 135 | + } |
| 136 | +} |
0 commit comments