File tree Expand file tree Collapse file tree 2 files changed +28
-3
lines changed
Sources/Request/Request/RequestParams Expand file tree Collapse file tree 2 files changed +28
-3
lines changed Original file line number Diff line number Diff line change @@ -24,6 +24,14 @@ import Foundation
24
24
/// Url("api.example.com/save")
25
25
/// Body("myData")
26
26
/// }
27
+ ///
28
+ /// Or as an `Encodable` type:
29
+ ///
30
+ /// Request {
31
+ /// Url("api.example.com/save")
32
+ /// Body(codableTodo)
33
+ /// }
34
+ ///
27
35
public struct Body : RequestParam {
28
36
public var type : RequestParamType = . body
29
37
public var value : Any ?
@@ -33,8 +41,17 @@ public struct Body: RequestParam {
33
41
self . value = try ? JSONSerialization . data ( withJSONObject: dict, options: . prettyPrinted)
34
42
}
35
43
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
+
36
49
/// Creates the `Body` from a `String`
37
50
public init ( _ string: String ) {
38
51
self . value = string. data ( using: . utf8)
39
52
}
40
53
}
54
+
55
+ #if canImport(SwiftUI)
56
+ public typealias RequestBody = Body
57
+ #endif
Original file line number Diff line number Diff line change @@ -43,17 +43,25 @@ final class RequestTests: XCTestCase {
43
43
}
44
44
45
45
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
+ }
48
51
performRequest ( Request {
49
52
Url ( " https://jsonplaceholder.typicode.com/todos " )
50
- method
53
+ Method ( . post )
51
54
Body ( [
52
55
" title " : " My Post " ,
53
56
" completed " : true ,
54
57
" userId " : 3 ,
55
58
] )
56
59
Body ( " { \" userId \" : 3, \" title \" : \" My Post \" , \" completed \" : true} " )
60
+ RequestBody ( Todo (
61
+ title: " My Post " ,
62
+ completed: true ,
63
+ userId: 3
64
+ ) )
57
65
} )
58
66
}
59
67
You can’t perform that action at this time.
0 commit comments