Skip to content

Use closure as fetch method to be aligned with other libraries #24

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 16 additions & 10 deletions Sources/SupabaseStorage/StorageApi.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,12 @@ import Foundation
public class StorageApi {
var url: String
var headers: [String: String]
var http: StorageHTTPClient
var session: StorageHTTPSession

init(url: String, headers: [String: String], http: StorageHTTPClient) {
init(url: String, headers: [String: String], session: StorageHTTPSession) {
self.url = url
self.headers = headers
self.http = http
// self.headers.merge(["Content-Type": "application/json"]) { $1 }
self.session = session
}

internal enum HTTPMethod: String {
Expand Down Expand Up @@ -49,14 +48,18 @@ public class StorageApi {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
}

let (data, response) = try await http.fetch(request)
if let mimeType = response.mimeType {
let (data, response) = try await session.fetch(request)
guard let httpResonse = response as? HTTPURLResponse else {
throw URLError(.badServerResponse)
}

if let mimeType = httpResonse.mimeType {
switch mimeType {
case "application/json":
let json = try JSONSerialization.jsonObject(with: data, options: [])
return try parse(response: json, statusCode: response.statusCode)
return try parse(response: json, statusCode: httpResonse.statusCode)
default:
return try parse(response: data, statusCode: response.statusCode)
return try parse(response: data, statusCode: httpResonse.statusCode)
}
} else {
throw StorageError(message: "failed to get response")
Expand Down Expand Up @@ -89,11 +92,14 @@ public class StorageApi {

request.setValue(formData.contentType, forHTTPHeaderField: "Content-Type")

let (data, response) = try await http.upload(request, from: formData.data)
let (data, response) = try await session.upload(request, formData.data)
guard let httpResonse = response as? HTTPURLResponse else {
throw URLError(.badServerResponse)
}

if jsonSerialization {
let json = try JSONSerialization.jsonObject(with: data, options: [])
return try parse(response: json, statusCode: response.statusCode)
return try parse(response: json, statusCode: httpResonse.statusCode)
}

if let dataString = String(data: data, encoding: .utf8) {
Expand Down
4 changes: 2 additions & 2 deletions Sources/SupabaseStorage/StorageBucketApi.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ public class StorageBucketApi: StorageApi {
/// - Parameters:
/// - url: Storage HTTP URL
/// - headers: HTTP headers.
override init(url: String, headers: [String: String], http: StorageHTTPClient) {
super.init(url: url, headers: headers, http: http)
override init(url: String, headers: [String: String], session: StorageHTTPSession) {
super.init(url: url, headers: headers, session: session)
self.headers.merge(["Content-Type": "application/json"]) { $1 }
}

Expand Down
4 changes: 2 additions & 2 deletions Sources/SupabaseStorage/StorageFileApi.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ public class StorageFileApi: StorageApi {
/// - url: Storage HTTP URL
/// - headers: HTTP headers.
/// - bucketId: The bucket id to operate on.
init(url: String, headers: [String: String], bucketId: String, http: StorageHTTPClient) {
init(url: String, headers: [String: String], bucketId: String, session: StorageHTTPSession) {
self.bucketId = bucketId
super.init(url: url, headers: headers, http: http)
super.init(url: url, headers: headers, session: session)
}

/// Uploads a file to an existing bucket.
Expand Down
70 changes: 18 additions & 52 deletions Sources/SupabaseStorage/StorageHTTPClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,59 +4,25 @@ import Foundation
import FoundationNetworking
#endif

public protocol StorageHTTPClient {
func fetch(_ request: URLRequest) async throws -> (Data, HTTPURLResponse)
func upload(_ request: URLRequest, from data: Data) async throws -> (Data, HTTPURLResponse)
}

public struct DefaultStorageHTTPClient: StorageHTTPClient {
public init() {}

public func fetch(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {
try await withCheckedThrowingContinuation { continuation in
let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
continuation.resume(throwing: error)
return
}

guard
let data = data,
let httpResponse = response as? HTTPURLResponse
else {
continuation.resume(throwing: URLError(.badServerResponse))
return
}

continuation.resume(returning: (data, httpResponse))
}

dataTask.resume()
}
public struct StorageHTTPSession: Sendable {
public let fetch: @Sendable (_ request: URLRequest) async throws -> (Data, URLResponse)
public let upload:
@Sendable (_ request: URLRequest, _ data: Data) async throws -> (Data, URLResponse)

public init(
fetch: @escaping @Sendable (_ request: URLRequest) async throws -> (Data, URLResponse),
upload: @escaping @Sendable (_ request: URLRequest, _ data: Data) async throws -> (
Data, URLResponse
)
) {
self.fetch = fetch
self.upload = upload
}

public func upload(
_ request: URLRequest,
from data: Data
) async throws -> (Data, HTTPURLResponse) {
try await withCheckedThrowingContinuation { continuation in
let task = URLSession.shared.uploadTask(with: request, from: data) { data, response, error in
if let error = error {
continuation.resume(throwing: error)
return
}

guard
let data = data,
let httpResponse = response as? HTTPURLResponse
else {
continuation.resume(throwing: URLError(.badServerResponse))
return
}

continuation.resume(returning: (data, httpResponse))
}
task.resume()
}
public init() {
self.init(
fetch: { try await URLSession.shared.data(for: $0) },
upload: { try await URLSession.shared.upload(for: $0, from: $1) }
)
}
}
8 changes: 5 additions & 3 deletions Sources/SupabaseStorage/SupabaseStorage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@ public class SupabaseStorageClient: StorageBucketApi {
/// - Parameters:
/// - url: Storage HTTP URL
/// - headers: HTTP headers.
override public init(url: String, headers: [String: String], http: StorageHTTPClient? = nil) {
super.init(url: url, headers: headers, http: http ?? DefaultStorageHTTPClient())
override public init(
url: String, headers: [String: String], session: StorageHTTPSession = .init()
) {
super.init(url: url, headers: headers, session: session)
}

/// Perform file operation in a bucket.
/// - Parameter id: The bucket id to operate on.
/// - Returns: StorageFileApi object
public func from(id: String) -> StorageFileApi {
StorageFileApi(url: url, headers: headers, bucketId: id, http: http)
StorageFileApi(url: url, headers: headers, bucketId: id, session: session)
}
}