/
ClientRequest.swift
95 lines (83 loc) 路 2.95 KB
/
ClientRequest.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
public struct ClientRequest {
public var method: HTTPMethod
public var url: URI
public var headers: HTTPHeaders
public var body: ByteBuffer?
public init(
method: HTTPMethod = .GET,
url: URI = "/",
headers: HTTPHeaders = [:],
body: ByteBuffer? = nil
) {
self.method = method
self.url = url
self.headers = headers
self.body = body
}
}
extension ClientRequest {
private struct _URLQueryContainer: URLQueryContainer {
var url: URI
func decode<D>(_ decodable: D.Type, using decoder: URLQueryDecoder) throws -> D
where D: Decodable
{
return try decoder.decode(D.self, from: self.url)
}
mutating func encode<E>(_ encodable: E, using encoder: URLQueryEncoder) throws
where E: Encodable
{
try encoder.encode(encodable, to: &self.url)
}
}
public var query: URLQueryContainer {
get {
return _URLQueryContainer(url: self.url)
}
set {
self.url = (newValue as! _URLQueryContainer).url
}
}
private struct _ContentContainer: ContentContainer {
var body: ByteBuffer?
var headers: HTTPHeaders
var contentType: HTTPMediaType? {
return self.headers.contentType
}
mutating func encode<E>(_ encodable: E, using encoder: ContentEncoder) throws where E : Encodable {
var body = ByteBufferAllocator().buffer(capacity: 0)
try encoder.encode(encodable, to: &body, headers: &self.headers)
self.body = body
}
func decode<D>(_ decodable: D.Type, using decoder: ContentDecoder) throws -> D where D : Decodable {
guard let body = self.body else {
throw Abort(.lengthRequired)
}
return try decoder.decode(D.self, from: body, headers: self.headers)
}
mutating func encode<C>(_ content: C, using encoder: ContentEncoder) throws where C : Content {
var content = content
try content.beforeEncode()
var body = ByteBufferAllocator().buffer(capacity: 0)
try encoder.encode(content, to: &body, headers: &self.headers)
self.body = body
}
func decode<C>(_ content: C.Type, using decoder: ContentDecoder) throws -> C where C : Content {
guard let body = self.body else {
throw Abort(.lengthRequired)
}
var decoded = try decoder.decode(C.self, from: body, headers: self.headers)
try decoded.afterDecode()
return decoded
}
}
public var content: ContentContainer {
get {
return _ContentContainer(body: self.body, headers: self.headers)
}
set {
let container = (newValue as! _ContentContainer)
self.body = container.body
self.headers = container.headers
}
}
}