Skip to content

Commit

Permalink
Add RequestBody typealias (#33)
Browse files Browse the repository at this point in the history
  • Loading branch information
carson-katri authored Jul 27, 2020
1 parent 703c333 commit 1b4493f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
17 changes: 17 additions & 0 deletions Sources/Request/Request/RequestParams/Body.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand All @@ -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<T: Encodable>(_ 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
14 changes: 11 additions & 3 deletions Tests/RequestTests/RequestTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
))
})
}

Expand Down

0 comments on commit 1b4493f

Please sign in to comment.