Fix API type checking and lint

This commit is contained in:
lucast committed 2026-10-07 00:53:14 +02:00
1 parent 3d07a77cb9
commit 36f2b2d843
5 files changed
+247 -59

No files matched your search

+48 -21
View File
@@ -15,11 +15,15 @@ public struct APIConfiguration: Sendable {
public func mediaURL(for path: String) -> URL? {
if let url = URL(string: path), url.scheme != nil { return url }
return URL(string: path.trimmingCharacters(in: CharacterSet(charactersIn: "/")), relativeTo: mediaBaseURL)?.absoluteURL
return URL(
string: path.trimmingCharacters(in: CharacterSet(charactersIn: "/")),
relativeTo: mediaBaseURL)?.absoluteURL
}
public func audioURL(for track: Track) -> URL? {
mediaURL(for: "\(track.fileDir.trimmingCharacters(in: CharacterSet(charactersIn: "/")))/high.m4a")
mediaURL(
for: "\(track.fileDir.trimmingCharacters(in: CharacterSet(charactersIn: "/")))/high.m4a"
)
}
}
@@ -34,9 +38,9 @@ public enum APIError: Error, LocalizedError, Sendable {
switch self {
case .invalidURL: "The API URL is invalid."
case .nonHTTPResponse: "The server returned an invalid response."
case let .http(status, message): message ?? "The server returned HTTP \(status)."
case let .decoding(message): "Could not read the server response: \(message)"
case let .transport(message): message
case .http(let status, let message): message ?? "The server returned HTTP \(status)."
case .decoding(let message): "Could not read the server response: \(message)"
case .transport(let message): message
}
}
}
@@ -70,7 +74,9 @@ public final class APIClient: @unchecked Sendable {
body: Body? = nil,
response: Response.Type = Response.self
) async throws -> Response {
try await perform(method, path: path, query: query, body: body, response: response, refreshAfterUnauthorized: true)
try await perform(
method, path: path, query: query, body: body, response: response,
refreshAfterUnauthorized: true)
}
private func perform<Response: Decodable & Sendable, Body: Encodable & Sendable>(
@@ -81,7 +87,10 @@ public final class APIClient: @unchecked Sendable {
response: Response.Type,
refreshAfterUnauthorized: Bool
) async throws -> Response {
guard var components = URLComponents(url: configuration.apiBaseURL.appending(path: path), resolvingAgainstBaseURL: false) else {
guard
var components = URLComponents(
url: configuration.apiBaseURL.appending(path: path), resolvingAgainstBaseURL: false)
else {
throw APIError.invalidURL
}
if !query.isEmpty { components.queryItems = query }
@@ -89,7 +98,9 @@ public final class APIClient: @unchecked Sendable {
var request = URLRequest(url: url)
request.httpMethod = method
request.setValue("application/json", forHTTPHeaderField: "Accept")
if let origin = URLComponents(url: configuration.apiBaseURL, resolvingAgainstBaseURL: false)?.url?.origin {
if let origin = URLComponents(
url: configuration.apiBaseURL, resolvingAgainstBaseURL: false)?.url?.origin
{
request.setValue(origin, forHTTPHeaderField: "Origin")
}
if let body {
@@ -100,7 +111,9 @@ public final class APIClient: @unchecked Sendable {
let (data, rawResponse) = try await session.data(for: request)
guard let http = rawResponse as? HTTPURLResponse else { throw APIError.nonHTTPResponse }
guard (200..<300).contains(http.statusCode) else {
let message = (try? JSONSerialization.jsonObject(with: data) as? [String: Any])?["message"] as? String
let message =
(try? JSONSerialization.jsonObject(with: data) as? [String: Any])?["message"]
as? String
if http.statusCode == 401, refreshAfterUnauthorized, !path.hasPrefix("auth/") {
let status: SessionStatus = try await perform(
"GET",
@@ -123,28 +136,42 @@ public final class APIClient: @unchecked Sendable {
}
throw APIError.http(status: http.statusCode, message: message)
}
if Response.self == EmptyResponse.self, let empty = EmptyResponse() as? Response { return empty }
if Response.self == EmptyResponse.self, let empty = EmptyResponse() as? Response {
return empty
}
do {
// The lyrics handler intentionally sends no body when lyrics are absent.
let isOptionalResponse = String(reflecting: Response.self).hasPrefix("Swift.Optional<")
if isOptionalResponse, data.isEmpty || (try? JSONSerialization.jsonObject(with: data) as? [String: Any])?.isEmpty == true {
let isOptionalResponse = String(reflecting: Response.self).hasPrefix(
"Swift.Optional<")
if isOptionalResponse,
data.isEmpty
|| (try? JSONSerialization.jsonObject(with: data) as? [String: Any])?
.isEmpty == true
{
return try decoder.decode(Response.self, from: Data("null".utf8))
}
return try decoder.decode(Response.self, from: data)
}
catch { throw APIError.decoding(error.localizedDescription) }
} catch let error as APIError { throw error }
catch { throw APIError.transport(error.localizedDescription) }
} catch { throw APIError.decoding(error.localizedDescription) }
} catch let error as APIError { throw error } catch {
throw APIError.transport(error.localizedDescription)
}
}
public func request<Response: Decodable & Sendable>(
_ method: String, path: String, query: [URLQueryItem] = [], response: Response.Type = Response.self
_ method: String, path: String, query: [URLQueryItem] = [],
response: Response.Type = Response.self
) async throws -> Response {
try await request(method, path: path, query: query, body: Optional<EmptyBody>.none, response: response)
try await request(
method, path: path, query: query, body: Optional<EmptyBody>.none, response: response)
}
private struct EmptyBody: Encodable, Sendable {}
public struct EmptyResponse: Decodable, Sendable { public init() {} }
nonisolated private struct EmptyBody: Encodable, Sendable {}
nonisolated public struct EmptyResponse: Decodable, Sendable { public init() {} }
}
private extension URL { var origin: String? { guard let scheme, let host else { return nil }; return "\(scheme)://\(host)" + (port.map { ":\($0)" } ?? "") } }
extension URL {
fileprivate var origin: String? {
guard let scheme, let host else { return nil }
return "\(scheme)://\(host)" + (port.map { ":\($0)" } ?? "")
}
}