From 1b4493f01e4d968ab17ed5e17a91a117a22d636f Mon Sep 17 00:00:00 2001 From: Carson Katri Date: Mon, 27 Jul 2020 09:55:42 -0400 Subject: [PATCH] Add RequestBody typealias (#33) --- .../Request/Request/RequestParams/Body.swift | 17 +++++++++++++++++ Tests/RequestTests/RequestTests.swift | 14 +++++++++++--- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/Sources/Request/Request/RequestParams/Body.swift b/Sources/Request/Request/RequestParams/Body.swift index 4b15cb2..cbd7d91 100644 --- a/Sources/Request/Request/RequestParams/Body.swift +++ b/Sources/Request/Request/RequestParams/Body.swift @@ -24,6 +24,14 @@ import Foundation /// Url("api.example.com/save") /// Body("myData") /// } +/// +/// Or as an `Encodable` type: +/// +/// Request { +/// Url("api.example.com/save") +/// Body(codableTodo) +/// } +/// public struct Body: RequestParam { public var type: RequestParamType = .body public var value: Any? @@ -33,8 +41,17 @@ public struct Body: RequestParam { self.value = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) } + /// Creates the `Body` from an `Encodable` type using `JSONEncoder` + public init(_ value: T) { + self.value = try? JSONEncoder().encode(value) + } + /// Creates the `Body` from a `String` public init(_ string: String) { self.value = string.data(using: .utf8) } } + +#if canImport(SwiftUI) +public typealias RequestBody = Body +#endif diff --git a/Tests/RequestTests/RequestTests.swift b/Tests/RequestTests/RequestTests.swift index b909482..4f5ae0c 100644 --- a/Tests/RequestTests/RequestTests.swift +++ b/Tests/RequestTests/RequestTests.swift @@ -43,17 +43,25 @@ final class RequestTests: XCTestCase { } func testPost() { - // Workaround for 'ambiguous reference' error. - let method = Method(.post) + struct Todo: Codable { + let title: String + let completed: Bool + let userId: Int + } performRequest(Request { Url("https://jsonplaceholder.typicode.com/todos") - method + Method(.post) Body([ "title": "My Post", "completed": true, "userId": 3, ]) Body("{\"userId\" : 3,\"title\" : \"My Post\",\"completed\" : true}") + RequestBody(Todo( + title: "My Post", + completed: true, + userId: 3 + )) }) }