Skip to content

Commit

Permalink
Add http-body parser for different bridges
Browse files Browse the repository at this point in the history
  • Loading branch information
ant013 committed Dec 17, 2024
1 parent 0bb7e77 commit 62f29da
Showing 1 changed file with 42 additions and 4 deletions.
46 changes: 42 additions & 4 deletions UnstoppableWallet/TonConnectAPI/Sources/TonConnectAPI/Client.swift
Original file line number Diff line number Diff line change
Expand Up @@ -134,19 +134,19 @@ public struct Client: APIProtocol {
switch response.status.code {
case 200:
let contentType = converter.extractContentTypeIfPresent(in: response.headerFields)
let body: Components.Responses.Response.Body
let bodyPayload: BodyUniversalData
if try contentType == nil
|| converter.isMatchingContentType(received: contentType, expectedRaw: "application/json")
{
body = try await converter.getResponseBodyAsJSON(
Components.Responses.Response.Body.jsonPayload.self,
bodyPayload = try await converter.getResponseBodyAsJSON(
JsonPayload.self,
from: responseBody,
transforming: { value in .json(value) }
)
} else {
throw converter.makeUnexpectedContentTypeError(contentType: contentType)
}
return .ok(.init(body: body))
return .ok(.init(body: .json(try bodyPayload.json)))
default:
let contentType = converter.extractContentTypeIfPresent(in: response.headerFields)
let body: Components.Responses.Response.Body
Expand All @@ -167,3 +167,41 @@ public struct Client: APIProtocol {
)
}
}

enum BodyUniversalData: Sendable, Hashable {

case json(JsonPayload)
public var json: Components.Responses.Response.Body.jsonPayload {
get throws {
switch self {
case let .json(body):
guard let message = body.message ?? body.status else {
throw ParsingError.cantParseBody
}
return .init(message: message, statusCode: body.statusCode ?? 200)
}
}
}
}

public struct JsonPayload: Codable, Hashable, Sendable {
public var message: String?
public var status: String?
public var statusCode: Int64?

public init(status: Swift.String?, message: String?, statusCode: Int64?) {
self.status = status
self.message = message
self.statusCode = statusCode
}

public enum CodingKeys: String, CodingKey {
case status
case message
case statusCode
}
}

public enum ParsingError: Error {
case cantParseBody
}

0 comments on commit 62f29da

Please sign in to comment.