From 97d1900d26272777f864803a0290573b39f47f00 Mon Sep 17 00:00:00 2001 From: Guilherme Souza Date: Fri, 5 Apr 2024 15:46:22 -0300 Subject: [PATCH] fix(postgrest): race condition when setting fetchOptions and execute method call (#325) --- Sources/PostgREST/PostgrestBuilder.swift | 19 ++++++++----------- Sources/_Helpers/Request.swift | 2 +- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/Sources/PostgREST/PostgrestBuilder.swift b/Sources/PostgREST/PostgrestBuilder.swift index 661d3167..9bef83e9 100644 --- a/Sources/PostgREST/PostgrestBuilder.swift +++ b/Sources/PostgREST/PostgrestBuilder.swift @@ -51,11 +51,7 @@ public class PostgrestBuilder: @unchecked Sendable { public func execute( options: FetchOptions = FetchOptions() ) async throws -> PostgrestResponse { - mutableState.withValue { - $0.fetchOptions = options - } - - return try await execute { _ in () } + try await execute(options: options) { _ in () } } /// Executes the request and returns a response of the specified type. @@ -66,11 +62,7 @@ public class PostgrestBuilder: @unchecked Sendable { public func execute( options: FetchOptions = FetchOptions() ) async throws -> PostgrestResponse { - mutableState.withValue { - $0.fetchOptions = options - } - - return try await execute { [configuration] data in + try await execute(options: options) { [configuration] data in do { return try configuration.decoder.decode(T.self, from: data) } catch { @@ -80,8 +72,13 @@ public class PostgrestBuilder: @unchecked Sendable { } } - private func execute(decode: (Data) throws -> T) async throws -> PostgrestResponse { + private func execute( + options: FetchOptions, + decode: (Data) throws -> T + ) async throws -> PostgrestResponse { mutableState.withValue { + $0.fetchOptions = options + if $0.fetchOptions.head { $0.request.method = .head } diff --git a/Sources/_Helpers/Request.swift b/Sources/_Helpers/Request.swift index 89cfe862..e9ee60e8 100644 --- a/Sources/_Helpers/Request.swift +++ b/Sources/_Helpers/Request.swift @@ -186,7 +186,7 @@ package struct Response: Sendable { package let data: Data package let response: HTTPURLResponse - public var statusCode: Int { + package var statusCode: Int { response.statusCode }