Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
7 changes: 7 additions & 0 deletions Sources/Helpers/SharedModels/PostgrestError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ public struct PostgrestError: Error, Codable, Sendable {
self.code = code
self.message = message
}

enum CodingKeys: String, CodingKey {
case detail = "details"
case hint
case code
case message
}
}

extension PostgrestError: LocalizedError {
Expand Down
31 changes: 31 additions & 0 deletions Tests/HelpersTests/PostgrestErrorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,35 @@ struct PostgrestErrorTests {
#expect(error.errorDescription == "test error message")
}

@Test
func decodesDetailsFromWireKey() throws {
let json = """
{
"code": "23505",
"details": "Key (id)=(1) already exists.",
"hint": "Use a different id.",
"message": "duplicate key value violates unique constraint \\"users_pkey\\""
}
"""

let error = try JSONDecoder().decode(PostgrestError.self, from: Data(json.utf8))

#expect(error.detail == "Key (id)=(1) already exists.")
#expect(error.hint == "Use a different id.")
#expect(error.code == "23505")
#expect(error.message == "duplicate key value violates unique constraint \"users_pkey\"")
}

@Test
func encodesDetailToWireKey() throws {
let error = PostgrestError(detail: "a detail", message: "a message")

let data = try JSONEncoder().encode(error)
let object = try #require(
try JSONSerialization.jsonObject(with: data) as? [String: Any]
)

#expect(object["details"] as? String == "a detail")
#expect(object["detail"] == nil)
}
}