Skip to content

Commit 78a9cca

Browse files
author
Guilherme Souza
committed
Share request logic between sub-packages
1 parent 2c78bb2 commit 78a9cca

File tree

11 files changed

+109
-133
lines changed

11 files changed

+109
-133
lines changed

.swiftpm/xcode/xcshareddata/xcschemes/Supabase.xcscheme

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<?xml version="1.0" encoding="UTF-8"?>
22
<Scheme
33
LastUpgradeVersion = "1500"
4-
version = "1.3">
4+
version = "1.7">
55
<BuildAction
66
parallelizeBuildables = "YES"
77
buildImplicitDependencies = "YES">

Sources/GoTrue/GoTrueClient.swift

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ public actor GoTrueClient {
204204
return try await _signUp(
205205
request: .init(
206206
path: "/signup",
207-
method: "POST",
207+
method: .post,
208208
query: [
209209
redirectTo.map { URLQueryItem(name: "redirect_to", value: $0.absoluteString) },
210210
].compactMap { $0 },
@@ -237,7 +237,7 @@ public actor GoTrueClient {
237237
try await _signUp(
238238
request: .init(
239239
path: "/signup",
240-
method: "POST",
240+
method: .post,
241241
body: configuration.encoder.encode(
242242
SignUpRequest(
243243
password: password,
@@ -271,7 +271,7 @@ public actor GoTrueClient {
271271
try await _signIn(
272272
request: .init(
273273
path: "/token",
274-
method: "POST",
274+
method: .post,
275275
query: [URLQueryItem(name: "grant_type", value: "password")],
276276
body: configuration.encoder.encode(
277277
UserCredentials(email: email, password: password)
@@ -286,7 +286,7 @@ public actor GoTrueClient {
286286
try await _signIn(
287287
request: .init(
288288
path: "/token",
289-
method: "POST",
289+
method: .post,
290290
query: [URLQueryItem(name: "grant_type", value: "password")],
291291
body: configuration.encoder.encode(
292292
UserCredentials(password: password, phone: phone)
@@ -302,7 +302,7 @@ public actor GoTrueClient {
302302
try await _signIn(
303303
request: .init(
304304
path: "/token",
305-
method: "POST",
305+
method: .post,
306306
query: [URLQueryItem(name: "grant_type", value: "id_token")],
307307
body: configuration.encoder.encode(credentials)
308308
)
@@ -350,7 +350,7 @@ public actor GoTrueClient {
350350
try await api.execute(
351351
.init(
352352
path: "/otp",
353-
method: "POST",
353+
method: .post,
354354
query: [
355355
redirectTo.map { URLQueryItem(name: "redirect_to", value: $0.absoluteString) },
356356
].compactMap { $0 },
@@ -385,7 +385,7 @@ public actor GoTrueClient {
385385
try await api.execute(
386386
.init(
387387
path: "/otp",
388-
method: "POST",
388+
method: .post,
389389
body: configuration.encoder.encode(
390390
OTPParams(
391391
phone: phone,
@@ -407,7 +407,7 @@ public actor GoTrueClient {
407407
let session: Session = try await api.execute(
408408
.init(
409409
path: "/token",
410-
method: "POST",
410+
method: .post,
411411
query: [URLQueryItem(name: "grant_type", value: "pkce")],
412412
body: configuration.encoder.encode(
413413
[
@@ -519,7 +519,7 @@ public actor GoTrueClient {
519519
let user = try await api.execute(
520520
.init(
521521
path: "/user",
522-
method: "GET",
522+
method: .get,
523523
headers: ["Authorization": "\(tokenType) \(accessToken)"]
524524
)
525525
).decoded(as: User.self, decoder: configuration.decoder)
@@ -593,7 +593,7 @@ public actor GoTrueClient {
593593
try await api.authorizedExecute(
594594
.init(
595595
path: "/logout",
596-
method: "POST"
596+
method: .post
597597
)
598598
)
599599
await sessionManager.remove()
@@ -616,7 +616,7 @@ public actor GoTrueClient {
616616
try await _verifyOTP(
617617
request: .init(
618618
path: "/verify",
619-
method: "POST",
619+
method: .post,
620620
query: [
621621
redirectTo.map { URLQueryItem(name: "redirect_to", value: $0.absoluteString) },
622622
].compactMap { $0 },
@@ -644,7 +644,7 @@ public actor GoTrueClient {
644644
try await _verifyOTP(
645645
request: .init(
646646
path: "/verify",
647-
method: "POST",
647+
method: .post,
648648
body: configuration.encoder.encode(
649649
VerifyOTPParams(
650650
phone: phone,
@@ -686,7 +686,7 @@ public actor GoTrueClient {
686686
/// Should be used only when you require the most current user data. For faster results,
687687
/// session.user is recommended.
688688
public func user(jwt: String? = nil) async throws -> User {
689-
var request = Request(path: "/user", method: "GET")
689+
var request = Request(path: "/user", method: .get)
690690

691691
if let jwt {
692692
request.headers["Authorization"] = "Bearer \(jwt)"
@@ -709,7 +709,7 @@ public actor GoTrueClient {
709709

710710
var session = try await sessionManager.session()
711711
let updatedUser = try await api.authorizedExecute(
712-
.init(path: "/user", method: "PUT", body: configuration.encoder.encode(user))
712+
.init(path: "/user", method: .put, body: configuration.encoder.encode(user))
713713
).decoded(as: User.self, decoder: configuration.decoder)
714714
session.user = updatedUser
715715
try await sessionManager.update(session)
@@ -728,7 +728,7 @@ public actor GoTrueClient {
728728
try await api.execute(
729729
.init(
730730
path: "/recover",
731-
method: "POST",
731+
method: .post,
732732
query: [
733733
redirectTo.map { URLQueryItem(name: "redirect_to", value: $0.absoluteString) },
734734
].compactMap { $0 },
@@ -759,7 +759,7 @@ public actor GoTrueClient {
759759
let session = try await api.execute(
760760
.init(
761761
path: "/token",
762-
method: "POST",
762+
method: .post,
763763
query: [URLQueryItem(name: "grant_type", value: "refresh_token")],
764764
body: configuration.encoder.encode(credentials)
765765
)

Sources/GoTrue/GoTrueMFA.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ public actor GoTrueMFA {
3333
public func enroll(params: MFAEnrollParams) async throws -> AuthMFAEnrollResponse {
3434
try await api.authorizedExecute(
3535
Request(
36-
path: "/factors", method: "POST",
36+
path: "/factors", method: .post,
3737
body: configuration.encoder.encode(params)
3838
)
3939
)
@@ -46,7 +46,7 @@ public actor GoTrueMFA {
4646
/// - Returns: An authentication response with the challenge information.
4747
public func challenge(params: MFAChallengeParams) async throws -> AuthMFAChallengeResponse {
4848
try await api.authorizedExecute(
49-
Request(path: "/factors/\(params.factorId)/challenge", method: "POST")
49+
Request(path: "/factors/\(params.factorId)/challenge", method: .post)
5050
)
5151
.decoded(decoder: configuration.decoder)
5252
}
@@ -59,7 +59,7 @@ public actor GoTrueMFA {
5959
public func verify(params: MFAVerifyParams) async throws -> AuthMFAVerifyResponse {
6060
let response: AuthMFAVerifyResponse = try await api.authorizedExecute(
6161
Request(
62-
path: "/factors/\(params.factorId)/verify", method: "POST",
62+
path: "/factors/\(params.factorId)/verify", method: .post,
6363
body: configuration.encoder.encode(params)
6464
)
6565
).decoded(decoder: configuration.decoder)
@@ -79,7 +79,7 @@ public actor GoTrueMFA {
7979
@discardableResult
8080
public func unenroll(params: MFAUnenrollParams) async throws -> AuthMFAUnenrollResponse {
8181
try await api.authorizedExecute(
82-
Request(path: "/factors/\(params.factorId)", method: "DELETE")
82+
Request(path: "/factors/\(params.factorId)", method: .delete)
8383
)
8484
.decoded(decoder: configuration.decoder)
8585
}

Sources/PostgREST/PostgrestBuilder.swift

Lines changed: 5 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -73,9 +73,9 @@ public class PostgrestBuilder: @unchecked Sendable {
7373
}
7474

7575
private func execute<T>(decode: (Data) throws -> T) async throws -> PostgrestResponse<T> {
76-
mutableState.withValue {
76+
let urlRequest = try mutableState.withValue {
7777
if $0.fetchOptions.head {
78-
$0.request.method = "HEAD"
78+
$0.request.method = .head
7979
}
8080

8181
if let count = $0.fetchOptions.count {
@@ -92,15 +92,15 @@ public class PostgrestBuilder: @unchecked Sendable {
9292
$0.request.headers["Content-Type"] = "application/json"
9393

9494
if let schema = configuration.schema {
95-
if $0.request.method == "GET" || $0.request.method == "HEAD" {
95+
if $0.request.method == .get || $0.request.method == .head {
9696
$0.request.headers["Accept-Profile"] = schema
9797
} else {
9898
$0.request.headers["Content-Profile"] = schema
9999
}
100100
}
101-
}
102101

103-
let urlRequest = try makeURLRequest()
102+
return try $0.request.urlRequest(withBaseURL: configuration.url)
103+
}
104104

105105
let (data, response) = try await configuration.fetch(urlRequest)
106106
guard let httpResponse = response as? HTTPURLResponse else {
@@ -115,82 +115,4 @@ public class PostgrestBuilder: @unchecked Sendable {
115115
let value = try decode(data)
116116
return PostgrestResponse(data: data, response: httpResponse, value: value)
117117
}
118-
119-
private func makeURLRequest() throws -> URLRequest {
120-
let request = mutableState.value.request
121-
122-
guard var components = URLComponents(
123-
url: configuration.url.appendingPathComponent(request.path),
124-
resolvingAgainstBaseURL: false
125-
) else {
126-
throw URLError(.badURL)
127-
}
128-
129-
if !request.query.isEmpty {
130-
let percentEncodedQuery =
131-
(components.percentEncodedQuery.map { $0 + "&" } ?? "") + query(request.query)
132-
components.percentEncodedQuery = percentEncodedQuery
133-
}
134-
135-
guard let url = components.url else {
136-
throw URLError(.badURL)
137-
}
138-
139-
var urlRequest = URLRequest(url: url)
140-
141-
for (key, value) in request.headers {
142-
urlRequest.setValue(value, forHTTPHeaderField: key)
143-
}
144-
145-
urlRequest.httpMethod = request.method
146-
147-
if let body = request.body {
148-
urlRequest.httpBody = body
149-
}
150-
151-
return urlRequest
152-
}
153-
154-
private func escape(_ string: String) -> String {
155-
string.addingPercentEncoding(withAllowedCharacters: .postgrestURLQueryAllowed) ?? string
156-
}
157-
158-
private func query(_ parameters: [URLQueryItem]) -> String {
159-
parameters.compactMap { query in
160-
if let value = query.value {
161-
return (query.name, value)
162-
}
163-
return nil
164-
}
165-
.map { name, value -> String in
166-
let escapedName = escape(name)
167-
let escapedValue = escape(value)
168-
return "\(escapedName)=\(escapedValue)"
169-
}
170-
.joined(separator: "&")
171-
}
172-
}
173-
174-
extension CharacterSet {
175-
/// Creates a CharacterSet from RFC 3986 allowed characters.
176-
///
177-
/// RFC 3986 states that the following characters are "reserved" characters.
178-
///
179-
/// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
180-
/// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
181-
///
182-
/// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to
183-
/// allow
184-
/// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?"
185-
/// and "/"
186-
/// should be percent-escaped in the query string.
187-
static let postgrestURLQueryAllowed: CharacterSet = {
188-
let generalDelimitersToEncode =
189-
":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
190-
let subDelimitersToEncode = "!$&'()*+,;="
191-
let encodableDelimiters =
192-
CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
193-
194-
return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters)
195-
}()
196118
}

Sources/PostgREST/PostgrestClient.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ public actor PostgrestClient {
102102
public func from(_ table: String) -> PostgrestQueryBuilder {
103103
PostgrestQueryBuilder(
104104
configuration: configuration,
105-
request: .init(path: table, method: "GET", headers: configuration.headers)
105+
request: .init(path: table, method: .get, headers: configuration.headers)
106106
)
107107
}
108108

@@ -121,7 +121,7 @@ public actor PostgrestClient {
121121
) throws -> PostgrestTransformBuilder {
122122
try PostgrestRpcBuilder(
123123
configuration: configuration,
124-
request: Request(path: "/rpc/\(fn)", method: "POST", headers: configuration.headers)
124+
request: Request(path: "/rpc/\(fn)", method: .post, headers: configuration.headers)
125125
).rpc(params: params, count: count)
126126
}
127127

Sources/PostgREST/PostgrestQueryBuilder.swift

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ public final class PostgrestQueryBuilder: PostgrestBuilder {
1414
count: CountOption? = nil
1515
) -> PostgrestFilterBuilder {
1616
mutableState.withValue {
17-
$0.request.method = "GET"
17+
$0.request.method = .get
1818
// remove whitespaces except when quoted.
1919
var quoted = false
2020
let cleanedColumns = columns.compactMap { char -> String? in
@@ -34,7 +34,7 @@ public final class PostgrestQueryBuilder: PostgrestBuilder {
3434
$0.request.headers["Prefer"] = "count=\(count.rawValue)"
3535
}
3636
if head {
37-
$0.request.method = "HEAD"
37+
$0.request.method = .head
3838
}
3939
}
4040

@@ -54,7 +54,7 @@ public final class PostgrestQueryBuilder: PostgrestBuilder {
5454
count: CountOption? = nil
5555
) throws -> PostgrestFilterBuilder {
5656
try mutableState.withValue {
57-
$0.request.method = "POST"
57+
$0.request.method = .post
5858
var prefersHeaders: [String] = []
5959
if let returning {
6060
prefersHeaders.append("return=\(returning.rawValue)")
@@ -100,7 +100,7 @@ public final class PostgrestQueryBuilder: PostgrestBuilder {
100100
ignoreDuplicates: Bool = false
101101
) throws -> PostgrestFilterBuilder {
102102
try mutableState.withValue {
103-
$0.request.method = "POST"
103+
$0.request.method = .post
104104
var prefersHeaders = [
105105
"resolution=\(ignoreDuplicates ? "ignore" : "merge")-duplicates",
106106
"return=\(returning.rawValue)",
@@ -135,7 +135,7 @@ public final class PostgrestQueryBuilder: PostgrestBuilder {
135135
count: CountOption? = nil
136136
) throws -> PostgrestFilterBuilder {
137137
try mutableState.withValue {
138-
$0.request.method = "PATCH"
138+
$0.request.method = .patch
139139
var preferHeaders = ["return=\(returning.rawValue)"]
140140
$0.request.body = try configuration.encoder.encode(values)
141141
if let count {
@@ -161,7 +161,7 @@ public final class PostgrestQueryBuilder: PostgrestBuilder {
161161
count: CountOption? = nil
162162
) -> PostgrestFilterBuilder {
163163
mutableState.withValue {
164-
$0.request.method = "DELETE"
164+
$0.request.method = .delete
165165
var preferHeaders = ["return=\(returning.rawValue)"]
166166
if let count {
167167
preferHeaders.append("count=\(count.rawValue)")

Sources/PostgREST/PostgrestRpcBuilder.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ public final class PostgrestRpcBuilder: PostgrestBuilder {
2222
assert(head == false, "HEAD is not currently supported yet.")
2323

2424
try mutableState.withValue {
25-
$0.request.method = "POST"
25+
$0.request.method = .post
2626
if params is NoParams {
2727
// noop
2828
} else {

Sources/Storage/StorageApi.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public class StorageApi {
3838

3939
extension Request {
4040
init(
41-
path: String, method: String, formData: FormData, options: FileOptions,
41+
path: String, method: Method, formData: FormData, options: FileOptions,
4242
headers: [String: String] = [:]
4343
) {
4444
var headers = headers

0 commit comments

Comments
 (0)