Skip to content

Refactor and improves PostgrestResponse type #10

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

Merged
merged 3 commits into from
Sep 1, 2021
Merged
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
23 changes: 3 additions & 20 deletions Sources/PostgREST/PostgrestBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,7 @@ public class PostgrestBuilder {
return
}

guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
throw PostgrestError(message: "failed to get error")
}

throw PostgrestError(from: json) ?? PostgrestError(message: "failed to get error")
throw try JSONDecoder().decode(PostgrestError.self, from: data)
}

/// Parses incoming data and server response into a `PostgrestResponse`
Expand All @@ -87,26 +83,15 @@ public class PostgrestBuilder {
/// - Throws: Throws an `Error` if invalid JSON.
/// - Returns: Returns a `PostgrestResponse`
private static func parse(data: Data, response: HTTPURLResponse, request: URLRequest) throws -> PostgrestResponse {
var body: Any = data
var count: Int?

if request.httpMethod == "HEAD" {
if let accept = response.allHeaderFields["Accept"] as? String, accept == "text/csv" {
body = data
} else {
try JSONSerialization.jsonObject(with: data, options: [])
}
}

if let contentRange = response.allHeaderFields["content-range"] as? String,
let lastElement = contentRange.split(separator: "/").last
{
count = lastElement == "*" ? nil : Int(lastElement)
}

let postgrestResponse = PostgrestResponse(body: body)
postgrestResponse.status = response.statusCode
postgrestResponse.count = count
let postgrestResponse = PostgrestResponse(data: data, status: response.statusCode, count: count)
return postgrestResponse
}

Expand All @@ -133,9 +118,7 @@ public class PostgrestBuilder {
throw PostgrestError(message: "Missing table operation: select, insert, update or delete")
}

// if method == "GET" || method == "HEAD" {
headers["Content-Type"] = "application/json"
// }

if let schema = schema {
if method == "GET" || method == "HEAD" {
Expand All @@ -144,7 +127,7 @@ public class PostgrestBuilder {
headers["Content-Profile"] = schema
}
}

guard var components = URLComponents(string: url) else {
throw PostgrestError(message: "badURL")
}
Expand Down
28 changes: 10 additions & 18 deletions Sources/PostgREST/PostgrestError.swift
Original file line number Diff line number Diff line change
@@ -1,23 +1,15 @@
import Foundation

public struct PostgrestError: Error {
public var details: String?
public var hint: String?
public var code: String?
public var message: String

init?(from dictionary: [String: Any]) {
guard let message = dictionary["message"] as? String else {
return nil
}

details = dictionary["details"] as? String
hint = dictionary["hint"] as? String
code = dictionary["code"] as? String
self.message = message
}

init(message: String) {
public struct PostgrestError: Error, Codable {
public let details: String?
public let hint: String?
public let code: String?
public let message: String

public init(details: String? = nil, hint: String? = nil, code: String? = nil, message: String) {
self.hint = hint
self.details = details
self.code = code
self.message = message
}
}
Expand Down
41 changes: 20 additions & 21 deletions Sources/PostgREST/PostgrestResponse.swift
Original file line number Diff line number Diff line change
@@ -1,29 +1,28 @@
public class PostgrestResponse {
public var body: Any
public var status: Int?
public var count: Int?
public var error: PostgrestError?
import Foundation

init(body: Any) {
self.body = body
public struct PostgrestResponse: Hashable {
public let data: Data
public let status: Int
public let count: Int?

public init(data: Data, status: Int, count: Int?) {
self.data = data
self.status = status
self.count = count
}
}

init?(from dictionary: [String: Any]) {
guard let body = dictionary["body"] else {
return nil
}
self.body = body
extension PostgrestResponse {

if let status: Int = dictionary["status"] as? Int {
self.status = status
}
public func json() throws -> Any {
try JSONSerialization.jsonObject(with: data, options: [.allowFragments])
}

if let count: Int = dictionary["count"] as? Int {
self.count = count
}
public func decoded<T: Decodable>(to type: T.Type = T.self, using decoder: JSONDecoder = JSONDecoder()) throws -> T {
try decoder.decode(type, from: data)
}

if let error: [String: Any] = dictionary["error"] as? [String: Any] {
self.error = PostgrestError(from: error)
}
public func string(encoding: String.Encoding = .utf8) -> String? {
String(data: data, encoding: encoding)
}
}
10 changes: 2 additions & 8 deletions Sources/example/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,8 @@ struct Todo: Codable {
database.from("todo").select().execute { result in
switch result {
case let .success(response):
guard let data = response.body as? Data else {
return
}
do {
let todos = try JSONDecoder().decode([Todo].self, from: data)
let todos = try response.decoded(to: [Todo].self)
print(todos)
} catch {
print(error.localizedDescription)
Expand All @@ -38,11 +35,8 @@ do {
database.from("todo").insert(values: jsonData).execute { result in
switch result {
case let .success(response):
guard let data = response.body as? Data else {
return
}
do {
let todos = try JSONDecoder().decode([Todo].self, from: data)
let todos = try response.decoded(to: [Todo].self)
print(todos)
} catch {
print(error.localizedDescription)
Expand Down