Skip to content

Commit 26bc1e1

Browse files
Merge pull request #6 from thecoolwinter/docs
Update README, add docs
2 parents c179942 + de46d28 commit 26bc1e1

File tree

4 files changed

+123
-9
lines changed

4 files changed

+123
-9
lines changed

README.md

+75
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,81 @@ Add `postgrest-swift` as a dependency to your `Package.swift` file. For more inf
1212
.package(url: "https://github.com/supabase/postgrest-swift", from: "0.1.0")
1313
```
1414

15+
### Supabase
16+
17+
You can also install the [ `supabase-swift`](https://github.com/supabase/supabase-swift) package to use the entire supabase library.
18+
19+
## Usage
20+
21+
Query todo table for all completed todos.
22+
```swift
23+
let client = PostgrestClient(url: "https://example.supabase.co", schema: nil)
24+
25+
do {
26+
let query = try client.from("todos")
27+
.select()
28+
.eq(column: "isDone", value: "true")
29+
try query.execute { [weak self] (results) in
30+
guard let self = self else { return }
31+
32+
// Handle results
33+
}
34+
} catch {
35+
print("Error querying for todos: \(error)")
36+
}
37+
```
38+
39+
Insert a todo into the database.
40+
```swift
41+
let client = PostgrestClient(url: "https://example.supabase.co", schema: nil)
42+
43+
struct Todo: Codable {
44+
var id: UUID = UUID()
45+
var label: String
46+
var isDone: Bool = false
47+
}
48+
49+
let todo = Todo(label: "Example todo!")
50+
51+
do {
52+
let jsonData: Data = try JSONEncoder().encode(todo)
53+
let jsonDict: [String: Any] = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments))
54+
55+
try client.from("todos")
56+
.insert(values: jsonDict)
57+
.execute { results in
58+
// Handle response
59+
}
60+
} catch {
61+
print("Error inserting the todo: \(error)")
62+
}
63+
```
64+
65+
For more query examples visit [the Javascript docs](https://supabase.io/docs/reference/javascript/select) to learn more. The API design is a near 1:1 match.
66+
67+
Execute an RPC
68+
```swift
69+
let client = PostgrestClient(url: "https://example.supabase.co", schema: nil)
70+
71+
do {
72+
try client.rpc(fn: "testFunction", parameters: nil).execute { result in
73+
// Handle result
74+
}
75+
} catch {
76+
print("Error executing the RPC: \(error)")
77+
}
78+
```
79+
80+
## Auth
81+
82+
You can add authentication to the databases requests by using the `client.headers` property. For example to add a `Bearer` auth header, simply set the headers dictionary to:
83+
```swift
84+
let client = PostgrestClient(url: "https://example.supabase.co",
85+
headers: ["Bearer": "{ Insert Token Here }"]
86+
schema: nil)
87+
```
88+
All requests made using this client will be sent with the `Bearer Token` header.
89+
1590
## Contributing
1691

1792
- Fork the repo on GitHub

Sources/PostgREST/PostgrestBuilder.swift

+26-4
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,12 @@ public class PostgrestBuilder {
1919
self.method = method
2020
self.body = body
2121
}
22-
22+
23+
/// Executes the built query or command.
24+
/// - Parameters:
25+
/// - head: If `true` use `HEAD` for the HTTP method when building the URLRequest. Defaults to `true`
26+
/// - count: A `CountOption` determining how many items to return. Defaults to `nil`
27+
/// - completion: Escaping completion handler with either a `PostgrestResponse` or an `Error`. Called after API call is completed and validated.
2328
public func execute(head: Bool = false, count: CountOption? = nil, completion: @escaping (Result<PostgrestResponse, Error>) -> Void) {
2429
let request: URLRequest
2530
do {
@@ -57,7 +62,12 @@ public class PostgrestBuilder {
5762

5863
dataTask.resume()
5964
}
60-
65+
66+
/// Validates the response from PostgREST
67+
/// - Parameters:
68+
/// - data: `Data` received from the server.
69+
/// - response: `HTTPURLResponse` received from the server.
70+
/// - Throws: Throws `PostgrestError` if invalid JSON object.
6171
private static func validate(data: Data, response: HTTPURLResponse) throws {
6272
if 200 ..< 300 ~= response.statusCode {
6373
return
@@ -69,7 +79,13 @@ public class PostgrestBuilder {
6979

7080
throw PostgrestError(from: json) ?? PostgrestError(message: "failed to get error")
7181
}
72-
82+
83+
/// Parses incoming data and server response into a `PostgrestResponse`
84+
/// - Parameters:
85+
/// - data: Data received from the server
86+
/// - response: Response received from the server
87+
/// - Throws: Throws an `Error` if invalid JSON.
88+
/// - Returns: Returns a `PostgrestResponse`
7389
private static func parse(data: Data, response: HTTPURLResponse, request: URLRequest) throws -> PostgrestResponse {
7490
var body: Any = data
7591
var count: Int?
@@ -92,7 +108,13 @@ public class PostgrestBuilder {
92108
postgrestResponse.count = count
93109
return postgrestResponse
94110
}
95-
111+
112+
/// Builds the URL request for PostgREST
113+
/// - Parameters:
114+
/// - head: If on, use `HEAD` as the HTTP method.
115+
/// - count: A `CountOption`,
116+
/// - Throws: Throws a `PostgressError`
117+
/// - Returns: Returns a valid URLRequest for the current query.
96118
func buildURLRequest(head: Bool, count: CountOption?) throws -> URLRequest {
97119
if head {
98120
method = "HEAD"

Sources/PostgREST/PostgrestClient.swift

+21-3
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,36 @@
1+
/**
2+
# PostgrestClient
3+
4+
This is the main class in this package. Use it to execute queries on a PostgREST instance on Supabase.
5+
*/
16
public class PostgrestClient {
27
var url: String
38
var headers: [String: String]
49
var schema: String?
5-
10+
11+
/// Initializes the `PostgrestClient` with the correct parameters.
12+
/// - Parameters:
13+
/// - url: Url of your supabase db instance
14+
/// - headers: Headers to include when querying the database. Eg, an authentication header
15+
/// - schema: Schema ID to use
616
public init(url: String, headers: [String: String] = [:], schema: String?) {
717
self.url = url
818
self.headers = headers
919
self.schema = schema
1020
}
11-
21+
22+
/// Select a table to query from
23+
/// - Parameter table: The ID of the table to query
24+
/// - Returns: `PostgrestQueryBuilder`
1225
public func form(_ table: String) -> PostgrestQueryBuilder {
1326
return PostgrestQueryBuilder(url: "\(url)/\(table)", queryParams: [], headers: headers, schema: schema, method: nil, body: nil)
1427
}
15-
28+
29+
/// Call a stored procedure, aka a "Remote Procedure Call"
30+
/// - Parameters:
31+
/// - fn: Procedure name to call.
32+
/// - parameters: Parameters to pass to the procedure.
33+
/// - Returns: `PostgrestTransformBuilder`
1634
public func rpc(fn: String, parameters: [String: Any]?) -> PostgrestTransformBuilder {
1735
return PostgrestRpcBuilder(url: "\(url)/rpc/\(fn)", queryParams: [], headers: headers, schema: schema, method: nil, body: nil).rpc(parameters: parameters)
1836
}

Tests/PostgRESTTests/BuildURLRequestTests.swift

+1-2
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,7 @@ final class BuildURLRequestTests: XCTestCase {
3232

3333
for testCase in testCases {
3434
let request = try testCase.build(client)
35-
assertSnapshot(
36-
matching: request, as: .curl, named: testCase.name, record: testCase.record)
35+
assertSnapshot(matching: request, as: .curl, named: testCase.name, record: testCase.record)
3736
}
3837
}
3938
}

0 commit comments

Comments
 (0)