Skip to content

Commit 1b4493f

Browse files
authored
Add RequestBody typealias (#33)
1 parent 703c333 commit 1b4493f

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

Sources/Request/Request/RequestParams/Body.swift

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,14 @@ import Foundation
2424
/// Url("api.example.com/save")
2525
/// Body("myData")
2626
/// }
27+
///
28+
/// Or as an `Encodable` type:
29+
///
30+
/// Request {
31+
/// Url("api.example.com/save")
32+
/// Body(codableTodo)
33+
/// }
34+
///
2735
public struct Body: RequestParam {
2836
public var type: RequestParamType = .body
2937
public var value: Any?
@@ -33,8 +41,17 @@ public struct Body: RequestParam {
3341
self.value = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
3442
}
3543

44+
/// Creates the `Body` from an `Encodable` type using `JSONEncoder`
45+
public init<T: Encodable>(_ value: T) {
46+
self.value = try? JSONEncoder().encode(value)
47+
}
48+
3649
/// Creates the `Body` from a `String`
3750
public init(_ string: String) {
3851
self.value = string.data(using: .utf8)
3952
}
4053
}
54+
55+
#if canImport(SwiftUI)
56+
public typealias RequestBody = Body
57+
#endif

Tests/RequestTests/RequestTests.swift

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,17 +43,25 @@ final class RequestTests: XCTestCase {
4343
}
4444

4545
func testPost() {
46-
// Workaround for 'ambiguous reference' error.
47-
let method = Method(.post)
46+
struct Todo: Codable {
47+
let title: String
48+
let completed: Bool
49+
let userId: Int
50+
}
4851
performRequest(Request {
4952
Url("https://jsonplaceholder.typicode.com/todos")
50-
method
53+
Method(.post)
5154
Body([
5255
"title": "My Post",
5356
"completed": true,
5457
"userId": 3,
5558
])
5659
Body("{\"userId\" : 3,\"title\" : \"My Post\",\"completed\" : true}")
60+
RequestBody(Todo(
61+
title: "My Post",
62+
completed: true,
63+
userId: 3
64+
))
5765
})
5866
}
5967

0 commit comments

Comments
 (0)