/
Request.swift
207 lines (175 loc) · 6.4 KB
/
Request.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import NIO
public final class Request: CustomStringConvertible {
public let application: Application
/// The HTTP method for this request.
///
/// httpReq.method = .GET
///
public var method: HTTPMethod
/// The URL used on this request.
public var url: URI
/// The version for this HTTP request.
public var version: HTTPVersion
/// The header fields for this HTTP request.
/// The `"Content-Length"` and `"Transfer-Encoding"` headers will be set automatically
/// when the `body` property is mutated.
public var headers: HTTPHeaders
internal var isKeepAlive: Bool
// MARK: Metadata
/// Route object we found for this request.
/// This holds metadata that can be used for (for example) Metrics.
///
/// req.route?.description // "GET /hello/:name"
///
public internal(set) var route: Route?
// MARK: Content
private struct _URLQueryContainer: URLQueryContainer {
let request: Request
func decode<D>(_ decodable: D.Type, using decoder: URLQueryDecoder) throws -> D
where D: Decodable
{
return try decoder.decode(D.self, from: self.request.url)
}
func encode<E>(_ encodable: E, using encoder: URLQueryEncoder) throws
where E: Encodable
{
try encoder.encode(encodable, to: &self.request.url)
}
}
public var query: URLQueryContainer {
get {
return _URLQueryContainer(request: self)
}
set {
// ignore since Request is a reference type
}
}
private struct _ContentContainer: ContentContainer {
let request: Request
var contentType: HTTPMediaType? {
return self.request.headers.contentType
}
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.request.headers)
self.request.bodyStorage = .collected(body)
}
func decode<D>(_ decodable: D.Type, using decoder: ContentDecoder) throws -> D where D : Decodable {
guard let body = self.request.body.data else {
self.request.logger.error("Decoding streaming bodies not supported")
throw Abort(.unprocessableEntity)
}
return try decoder.decode(D.self, from: body, headers: self.request.headers)
}
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.request.headers)
self.request.bodyStorage = .collected(body)
}
func decode<C>(_ content: C.Type, using decoder: ContentDecoder) throws -> C where C : Content {
guard let body = self.request.body.data else {
self.request.logger.error("Decoding streaming bodies not supported")
throw Abort(.unprocessableEntity)
}
var decoded = try decoder.decode(C.self, from: body, headers: self.request.headers)
try decoded.afterDecode()
return decoded
}
}
public var content: ContentContainer {
get {
return _ContentContainer(request: self)
}
set {
// ignore since Request is a reference type
}
}
public var logger: Logger
public var body: Body {
return Body(self)
}
internal enum BodyStorage {
case none
case collected(ByteBuffer)
case stream(BodyStream)
}
internal var bodyStorage: BodyStorage
/// Get and set `HTTPCookies` for this `HTTPRequest`
/// This accesses the `"Cookie"` header.
public var cookies: HTTPCookies {
get {
return self.headers.cookie ?? .init()
}
set {
self.headers.cookie = newValue
}
}
/// See `CustomStringConvertible`
public var description: String {
var desc: [String] = []
desc.append("\(self.method) \(self.url) HTTP/\(self.version.major).\(self.version.minor)")
desc.append(self.headers.debugDescription)
desc.append(self.body.description)
return desc.joined(separator: "\n")
}
public let remoteAddress: SocketAddress?
public let eventLoop: EventLoop
public var parameters: Parameters
public var storage: Storage
public convenience init(
application: Application,
method: HTTPMethod = .GET,
url: URI = "/",
version: HTTPVersion = .init(major: 1, minor: 1),
headers: HTTPHeaders = .init(),
collectedBody: ByteBuffer? = nil,
remoteAddress: SocketAddress? = nil,
logger: Logger = .init(label: "codes.vapor.request"),
on eventLoop: EventLoop
) {
self.init(
application: application,
method: method,
url: url,
version: version,
headersNoUpdate: headers,
collectedBody: collectedBody,
logger: logger,
on: eventLoop
)
if let body = collectedBody {
self.headers.updateContentLength(body.readableBytes)
}
}
public init(
application: Application,
method: HTTPMethod,
url: URI,
version: HTTPVersion = .init(major: 1, minor: 1),
headersNoUpdate headers: HTTPHeaders = .init(),
collectedBody: ByteBuffer? = nil,
remoteAddress: SocketAddress? = nil,
logger: Logger = .init(label: "codes.vapor.request"),
on eventLoop: EventLoop
) {
self.application = application
self.method = method
self.url = url
self.version = version
self.headers = headers
if let body = collectedBody {
self.bodyStorage = .collected(body)
} else {
self.bodyStorage = .none
}
self.remoteAddress = remoteAddress
self.eventLoop = eventLoop
self.parameters = .init()
self.storage = .init()
self.isKeepAlive = true
self.logger = logger
self.logger[metadataKey: "request-id"] = .string(UUID().uuidString)
}
}