Skip to content

Commit

Permalink
fix Test
Browse files Browse the repository at this point in the history
  • Loading branch information
zunda-pixel committed Nov 30, 2024
1 parent 1b370ff commit 5bba6e3
Show file tree
Hide file tree
Showing 87 changed files with 546 additions and 405 deletions.
8 changes: 5 additions & 3 deletions Sources/Auth/AuthClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1122,10 +1122,12 @@ public final class AuthClient: Sendable {

if let jwt {
request.headerFields[.authorization] = "Bearer \(jwt)"
let (data, _) = try await api.execute(for: request, from: nil)
return try configuration.decoder.decode(User.self, from: data)
} else {
let (data, _) = try await api.authorizedExecute(for: request, from: nil)
return try configuration.decoder.decode(User.self, from: data)
}

let (data, _) = try await api.authorizedExecute(for: request, from: nil)
return try configuration.decoder.decode(User.self, from: data)
}

/// Updates user data, if there is a logged in user.
Expand Down
2 changes: 1 addition & 1 deletion Sources/Auth/AuthClientConfiguration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ extension AuthClient {
},
autoRefreshToken: Bool = AuthClient.Configuration.defaultAutoRefreshToken
) {
let headers = headers.merging(with: Configuration.defaultHeaders)
let headers = Configuration.defaultHeaders.merging(headers) { $1 }

self.url = url ?? defaultAuthURL
self.headers = headers
Expand Down
7 changes: 2 additions & 5 deletions Sources/Auth/Internal/APIClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,9 @@ struct APIClient: Sendable {
func execute(
for request: HTTPRequest,
from bodyData: Data?
) async throws -> (
Data,
HTTPResponse
) {
) async throws -> (Data, HTTPResponse) {
var request = request
request.headerFields = HTTPFields(configuration.headers).merging(with: request.headerFields)
request.headerFields = request.headerFields.merging(configuration.headers) { $1 }

if request.headerFields[.apiVersionHeaderName] == nil {
request.headerFields[.apiVersionHeaderName] = apiVersions[._20240101]!.name.rawValue
Expand Down
6 changes: 5 additions & 1 deletion Sources/Functions/FunctionsClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -236,8 +236,12 @@ public final class FunctionsClient: Sendable {
url: url
.appendingPathComponent(functionName)
.appendingQueryItems(options.query),
headerFields: mutableState.headers.merging(with: options.headers)
headerFields: mutableState.headers.merging(options.headers) { $1 }
)

if options.body != nil && request.headerFields[.contentType] == nil {
request.headerFields[.contentType] = "application/json"
}

if let region = options.region ?? region {
request.headerFields[.xRegion] = region
Expand Down
2 changes: 1 addition & 1 deletion Sources/Functions/Types.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public struct FunctionInvokeOptions: Sendable {
}

self.method = method
self.headers = defaultHeaders.merging(with: headers)
self.headers = defaultHeaders.merging(headers) { $1 }
self.region = region
self.query = query
}
Expand Down
8 changes: 6 additions & 2 deletions Sources/Helpers/HTTP/HTTPClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,12 @@ package actor HTTPClient: HTTPClientType {
_ request: HTTPRequest,
_ bodyData: Data?
) async throws -> (Data, HTTPResponse) {
var next: @Sendable (HTTPRequest, Data?) async throws -> (Data, HTTPResponse) = {
return try await self.fetch($0, $1)
var next: @Sendable (HTTPRequest, Data?) async throws -> (Data, HTTPResponse) = { request, bodyData in
var request = request
if bodyData != nil && request.headerFields[.contentType] == nil {
request.headerFields[.contentType] = "application/json"
}
return try await self.fetch(request, bodyData)
}

for interceptor in interceptors.reversed() {
Expand Down
18 changes: 11 additions & 7 deletions Sources/Helpers/HTTP/HTTPFields.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,21 @@ extension HTTPFields {
return .init(keyValues, uniquingKeysWith: { $1 })
}

package mutating func merge(with other: Self) {
for field in other {
self[field.name] = field.value
}
package mutating func merge(
_ other: Self,
uniquingKeysWith combine: (String, String) throws -> String
) rethrows {
self = try self.merging(other, uniquingKeysWith: combine)
}

package func merging(with other: Self) -> Self {

package func merging(
_ other: Self,
uniquingKeysWith combine: (String, String) throws -> String
) rethrows -> HTTPFields {
var copy = self

for field in other {
copy[field.name] = field.value
copy[field.name] = try combine(self[field.name] ?? "", field.value)
}

return copy
Expand Down
4 changes: 4 additions & 0 deletions Sources/Helpers/HTTP/LoggerInterceptor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ package struct LoggerInterceptor: HTTPClientInterceptor {
)

do {
var request = request
if bodyData != nil && request.headerFields[.contentType] == nil {
request.headerFields[.contentType] = "application/json"
}
let (data, response) = try await next(request, bodyData)
logger.verbose(
"""
Expand Down
113 changes: 113 additions & 0 deletions Sources/Helpers/HTTP/URLSession+HTTPRequest.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import Foundation
import HTTPTypes

#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

#if !os(WASI)

extension URLSessionTask {
/// The original HTTP request this task was created with.
public var originalHTTPRequest: HTTPRequest? {
self.originalRequest?.httpRequest
}

/// The current HTTP request -- may differ from the `originalHTTPRequest` due to HTTP redirection.
public var currentHTTPRequest: HTTPRequest? {
self.currentRequest?.httpRequest
}

/// The HTTP response received from the server.
public var httpResponse: HTTPResponse? {
(self.response as? HTTPURLResponse)?.httpResponse
}
}

private enum HTTPTypeConversionError: Error {
case failedToConvertHTTPRequestToURLRequest
case failedToConvertURLResponseToHTTPResponse
}

#endif

#if canImport(FoundationNetworking) && compiler(<6)

@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
extension URLSession {
/// Convenience method to load data using an `HTTPRequest`; creates and resumes a `URLSessionDataTask` internally.
///
/// - Parameter request: The `HTTPRequest` for which to load data.
/// - Parameter delegate: Task-specific delegate.
/// - Returns: Data and response.
public func data(
for request: HTTPRequest,
delegate: (any URLSessionTaskDelegate)? = nil
) async throws -> (Data, HTTPResponse) {
guard let urlRequest = URLRequest(httpRequest: request) else {
throw HTTPTypeConversionError.failedToConvertHTTPRequestToURLRequest
}
let (data, urlResponse) = try await self.data(for: urlRequest, delegate: delegate)
guard let response = (urlResponse as? HTTPURLResponse)?.httpResponse else {
throw HTTPTypeConversionError.failedToConvertURLResponseToHTTPResponse
}
return (data, response)
}

/// Convenience method to upload data using an `HTTPRequest`, creates and resumes a `URLSessionUploadTask` internally.
///
/// - Parameter request: The `HTTPRequest` for which to upload data.
/// - Parameter bodyData: Data to upload.
/// - Parameter delegate: Task-specific delegate.
/// - Returns: Data and response.
public func upload(
for request: HTTPRequest,
from bodyData: Data,
delegate: (any URLSessionTaskDelegate)? = nil
) async throws -> (Data, HTTPResponse) {
guard let urlRequest = URLRequest(httpRequest: request) else {
throw HTTPTypeConversionError.failedToConvertHTTPRequestToURLRequest
}
let (data, urlResponse) = try await self.upload(for: urlRequest, from: bodyData, delegate: delegate)
guard let response = (urlResponse as? HTTPURLResponse)?.httpResponse else {
throw HTTPTypeConversionError.failedToConvertURLResponseToHTTPResponse
}
return (data, response)
}
}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension URLSession {
/// Convenience method to load data using an `HTTPRequest`; creates and resumes a `URLSessionDataTask` internally.
///
/// - Parameter request: The `HTTPRequest` for which to load data.
/// - Returns: Data and response.
public func data(for request: HTTPRequest) async throws -> (Data, HTTPResponse) {
guard let urlRequest = URLRequest(httpRequest: request) else {
throw HTTPTypeConversionError.failedToConvertHTTPRequestToURLRequest
}
let (data, urlResponse) = try await self.data(for: urlRequest)
guard let response = (urlResponse as? HTTPURLResponse)?.httpResponse else {
throw HTTPTypeConversionError.failedToConvertURLResponseToHTTPResponse
}
return (data, response)
}

/// Convenience method to upload data using an `HTTPRequest`, creates and resumes a `URLSessionUploadTask` internally.
///
/// - Parameter request: The `HTTPRequest` for which to upload data.
/// - Parameter bodyData: Data to upload.
/// - Returns: Data and response.
public func upload(for request: HTTPRequest, from bodyData: Data) async throws -> (Data, HTTPResponse) {
guard let urlRequest = URLRequest(httpRequest: request) else {
throw HTTPTypeConversionError.failedToConvertHTTPRequestToURLRequest
}
let (data, urlResponse) = try await self.upload(for: urlRequest, from: bodyData)
guard let response = (urlResponse as? HTTPURLResponse)?.httpResponse else {
throw HTTPTypeConversionError.failedToConvertURLResponseToHTTPResponse
}
return (data, response)
}
}

#endif
6 changes: 3 additions & 3 deletions Sources/PostgREST/PostgrestBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public class PostgrestBuilder: @unchecked Sendable {
options: FetchOptions,
decode: (Data) throws -> T
) async throws -> PostgrestResponse<T> {
let request = mutableState.withValue {
let (request, bodyData) = mutableState.withValue {
$0.fetchOptions = options

if $0.fetchOptions.head {
Expand Down Expand Up @@ -130,10 +130,10 @@ public class PostgrestBuilder: @unchecked Sendable {
}
}

return $0.request
return ($0.request, $0.bodyData)
}

let (data, response) = try await http.send(request, nil)
let (data, response) = try await http.send(request, bodyData)

guard 200..<300 ~= response.status.code else {
if let error = try? configuration.decoder.decode(PostgrestError.self, from: data) {
Expand Down
2 changes: 1 addition & 1 deletion Sources/PostgREST/PostgrestClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public final class PostgrestClient: Sendable {
public init(configuration: Configuration) {
_configuration = LockIsolated(configuration)
_configuration.withValue {
$0.headers.merge(with: Configuration.defaultHeaders)
$0.headers.merge(Configuration.defaultHeaders) { l, _ in l }
}
}

Expand Down
1 change: 0 additions & 1 deletion Sources/Realtime/PhoenixTransport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,6 @@ open class URLSessionTransport: NSObject, PhoenixTransport, URLSessionWebSocketD
var request = URLRequest(url: url)

for (key, value) in headers {
guard let value = value as? String else { continue }
request.addValue(value, forHTTPHeaderField: key)
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/Storage/StorageApi.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public class StorageApi: @unchecked Sendable {
from bodyData: Data?
) async throws -> (Data, HTTPResponse) {
var request = request
request.headerFields = configuration.headers.merging(with: request.headerFields)
request.headerFields = configuration.headers.merging(request.headerFields) { $1 }

let (data, response) = try await http.send(request, bodyData)

Expand Down
4 changes: 2 additions & 2 deletions Sources/Storage/StorageFileApi.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public class StorageFileApi: StorageApi, @unchecked Sendable {
options: FileOptions?
) async throws -> FileUploadResponse {
let options = options ?? defaultFileOptions
var headers = options.headers.map { HTTPFields($0) } ?? HTTPFields()
var headers = options.headers ?? HTTPFields()

if method == .post {
headers[.xUpsert] = "\(options.upsert)"
Expand Down Expand Up @@ -647,7 +647,7 @@ public class StorageFileApi: StorageApi, @unchecked Sendable {
options: FileOptions?
) async throws -> SignedURLUploadResponse {
let options = options ?? defaultFileOptions
var headers = options.headers.map { HTTPFields($0) } ?? HTTPFields()
var headers = options.headers ?? HTTPFields()

headers[.xUpsert] = "\(options.upsert)"
headers[.duplex] = options.duplex
Expand Down
23 changes: 10 additions & 13 deletions Sources/Supabase/SupabaseClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public final class SupabaseClient: Sendable {
$0.rest = PostgrestClient(
url: databaseURL,
schema: options.db.schema,
headers: _headers,
headers: headers,
logger: options.global.logger,
fetch: { request, bodyData in
if let bodyData {
Expand All @@ -72,7 +72,7 @@ public final class SupabaseClient: Sendable {
$0.storage = SupabaseStorageClient(
configuration: StorageClientConfiguration(
url: storageURL,
headers: _headers,
headers: headers,
session: StorageHTTPSession { request, bodyData in
if let bodyData {
return try await self.uploadWithAuth(for: request, from: bodyData)
Expand Down Expand Up @@ -100,7 +100,7 @@ public final class SupabaseClient: Sendable {
if $0.functions == nil {
$0.functions = FunctionsClient(
url: functionsURL,
headers: _headers,
headers: headers,
region: options.functions.region,
logger: options.global.logger,
fetch: { request, bodyData in
Expand All @@ -116,14 +116,11 @@ public final class SupabaseClient: Sendable {
return $0.functions!
}
}

let _headers: HTTPFields

/// Headers provided to the inner clients on initialization.
///
/// - Note: This collection is non-mutable, if you want to provide different headers, pass it in ``SupabaseClientOptions/GlobalOptions/headers``.
public var headers: [String: String] {
_headers.dictionary
}
public let headers: HTTPFields

struct MutableState {
var listenForAuthEventsTask: Task<Void, Never>?
Expand Down Expand Up @@ -177,14 +174,14 @@ public final class SupabaseClient: Sendable {
.authorization: "Bearer \(supabaseKey)",
.apiKey: supabaseKey,
]
_headers = headers.merging(with: options.global.headers)
self.headers = options.global.headers.merging(headers) { $1 }

// default storage key uses the supabase project ref as a namespace
let defaultStorageKey = "sb-\(supabaseURL.host!.split(separator: ".")[0])-auth-token"

_auth = AuthClient(
url: supabaseURL.appendingPathComponent("/auth/v1"),
headers: _headers,
headers: self.headers,
flowType: options.auth.flowType,
redirectToURL: options.auth.redirectToURL,
storageKey: options.auth.storageKey ?? defaultStorageKey,
Expand All @@ -206,13 +203,13 @@ public final class SupabaseClient: Sendable {
_realtime = UncheckedSendable(
RealtimeClient(
supabaseURL.appendingPathComponent("/realtime/v1").absoluteString,
headers: _headers,
params: _headers.dictionary
headers: headers,
params: headers.dictionary
)
)

var realtimeOptions = options.realtime
realtimeOptions.headers.merge(with: _headers)
realtimeOptions.headers.merge(self.headers) { $1 }
if realtimeOptions.logger == nil {
realtimeOptions.logger = options.global.logger
}
Expand Down
Loading

0 comments on commit 5bba6e3

Please sign in to comment.