/
URLEncodedFormEncoder.swift
401 lines (356 loc) · 15.5 KB
/
URLEncodedFormEncoder.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/// Encodes `Encodable` instances to `application/x-www-form-urlencoded` data.
///
/// print(user) /// User
/// let data = try URLEncodedFormEncoder().encode(user)
/// print(data) /// Data
///
/// URL-encoded forms are commonly used by websites to send form data via POST requests. This encoding is relatively
/// efficient for small amounts of data but must be percent-encoded. `multipart/form-data` is more efficient for sending
/// large data blobs like files.
///
/// See [Mozilla's](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) docs for more information about
/// url-encoded forms.
/// NOTE: This implementation of the encoder does not support encoding booleans to "flags".
public struct URLEncodedFormEncoder: ContentEncoder, URLQueryEncoder {
/// Used to capture URLForm Coding Configuration used for encoding.
public struct Configuration {
/// Supported array encodings.
public enum ArrayEncoding {
/// Arrays are serialized as separate values with bracket suffixed keys.
/// For example, `foo = [1,2,3]` would be serialized as `foo[]=1&foo[]=2&foo[]=3`.
case bracket
/// Arrays are serialized as a single value with character-separated items.
/// For example, `foo = [1,2,3]` would be serialized as `foo=1,2,3`.
case separator(Character)
/// Arrays are serialized as separate values.
/// For example, `foo = [1,2,3]` would be serialized as `foo=1&foo=2&foo=3`.
case values
}
/// Supported date formats
public enum DateEncodingStrategy {
/// Seconds since 1 January 1970 00:00:00 UTC (Unix Timestamp)
case secondsSince1970
/// ISO 8601 formatted date
case iso8601
/// Using custom callback
case custom((Date, Encoder) throws -> Void)
}
/// Specified array encoding.
public var arrayEncoding: ArrayEncoding
public var dateEncodingStrategy: DateEncodingStrategy
/// Creates a new `Configuration`.
///
/// - parameters:
/// - arrayEncoding: Specified array encoding. Defaults to `.bracket`.
/// - dateFormat: Format to encode date format too. Defaults to `secondsSince1970`
public init(
arrayEncoding: ArrayEncoding = .bracket,
dateEncodingStrategy: DateEncodingStrategy = .secondsSince1970
) {
self.arrayEncoding = arrayEncoding
self.dateEncodingStrategy = dateEncodingStrategy
}
}
private let configuration: Configuration
/// Create a new `URLEncodedFormEncoder`.
///
/// ContentConfiguration.global.use(urlEncoder: URLEncodedFormEncoder(bracketsAsArray: true, flagsAsBool: true, arraySeparator: nil))
///
/// - parameters:
/// - configuration: Defines how encoding is done see `URLEncodedFormCodingConfig` for more information
public init(
configuration: Configuration = .init()
) {
self.configuration = configuration
}
/// `ContentEncoder` conformance.
public func encode<E>(_ encodable: E, to body: inout ByteBuffer, headers: inout HTTPHeaders) throws
where E: Encodable
{
headers.contentType = .urlEncodedForm
try body.writeString(self.encode(encodable))
}
/// `URLContentEncoder` conformance.
public func encode<E>(_ encodable: E, to url: inout URI) throws
where E: Encodable
{
url.query = try self.encode(encodable)
}
/// Encodes the supplied `Encodable` object to `Data`.
///
/// print(user) // User
/// let data = try URLEncodedFormEncoder().encode(user)
/// print(data) // "name=Vapor&age=3"
///
/// - parameters:
/// - encodable: Generic `Encodable` object (`E`) to encode.
/// - configuration: Overwrides the coding config for this encoding call.
/// - returns: Encoded `Data`
/// - throws: Any error that may occur while attempting to encode the specified type.
public func encode<E>(_ encodable: E) throws -> String
where E: Encodable
{
let encoder = _Encoder(codingPath: [], configuration: self.configuration)
try encodable.encode(to: encoder)
let serializer = URLEncodedFormSerializer()
return try serializer.serialize(encoder.getData())
}
}
// MARK: Private
private protocol _Container {
func getData() throws -> URLEncodedFormData
}
private class _Encoder: Encoder {
var codingPath: [CodingKey]
private var container: _Container? = nil
func getData() throws -> URLEncodedFormData {
return try container?.getData() ?? []
}
var userInfo: [CodingUserInfoKey: Any] {
return [:]
}
private let configuration: URLEncodedFormEncoder.Configuration
init(codingPath: [CodingKey], configuration: URLEncodedFormEncoder.Configuration) {
self.codingPath = codingPath
self.configuration = configuration
}
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey {
let container = KeyedContainer<Key>(codingPath: codingPath, configuration: configuration)
self.container = container
return .init(container)
}
func unkeyedContainer() -> UnkeyedEncodingContainer {
let container = UnkeyedContainer(codingPath: codingPath, configuration: configuration)
self.container = container
return container
}
func singleValueContainer() -> SingleValueEncodingContainer {
let container = SingleValueContainer(codingPath: codingPath, configuration: configuration)
self.container = container
return container
}
private final class KeyedContainer<Key>: KeyedEncodingContainerProtocol, _Container
where Key: CodingKey
{
var codingPath: [CodingKey]
var internalData: URLEncodedFormData = []
var childContainers: [String: _Container] = [:]
func getData() throws -> URLEncodedFormData {
var result = internalData
for (key, childContainer) in self.childContainers {
result.children[key] = try childContainer.getData()
}
return result
}
private let configuration: URLEncodedFormEncoder.Configuration
init(
codingPath: [CodingKey],
configuration: URLEncodedFormEncoder.Configuration
) {
self.codingPath = codingPath
self.configuration = configuration
}
/// See `KeyedEncodingContainerProtocol`
func encodeNil(forKey key: Key) throws {
// skip
}
private func encodeDate(_ date: Date, forKey key: Key) throws {
switch configuration.dateEncodingStrategy {
case .secondsSince1970:
internalData.children[key.stringValue] = URLEncodedFormData(values: [date.urlQueryFragmentValue])
case .iso8601:
internalData.children[key.stringValue] = URLEncodedFormData(values: [
ISO8601DateFormatter.threadSpecific.string(from: date).urlQueryFragmentValue
])
case .custom(let callback):
let encoder = _Encoder(codingPath: self.codingPath + [key], configuration: self.configuration)
try callback(date, encoder)
self.internalData.children[key.stringValue] = try encoder.getData()
}
}
/// See `KeyedEncodingContainerProtocol`
func encode<T>(_ value: T, forKey key: Key) throws
where T : Encodable
{
if let date = value as? Date {
try encodeDate(date, forKey: key)
} else if let convertible = value as? URLQueryFragmentConvertible {
internalData.children[key.stringValue] = URLEncodedFormData(values: [convertible.urlQueryFragmentValue])
} else {
let encoder = _Encoder(codingPath: self.codingPath + [key], configuration: self.configuration)
try value.encode(to: encoder)
self.internalData.children[key.stringValue] = try encoder.getData()
}
}
/// See `KeyedEncodingContainerProtocol`
func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey>
where NestedKey: CodingKey
{
let container = KeyedContainer<NestedKey>(
codingPath: self.codingPath + [key],
configuration: self.configuration
)
self.childContainers[key.stringValue] = container
return .init(container)
}
/// See `KeyedEncodingContainerProtocol`
func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
let container = UnkeyedContainer(
codingPath: self.codingPath + [key],
configuration: self.configuration
)
self.childContainers[key.stringValue] = container
return container
}
/// See `KeyedEncodingContainerProtocol`
func superEncoder() -> Encoder {
fatalError()
}
/// See `KeyedEncodingContainerProtocol`
func superEncoder(forKey key: Key) -> Encoder {
fatalError()
}
}
/// Private `UnkeyedEncodingContainer`.
private final class UnkeyedContainer: UnkeyedEncodingContainer, _Container {
var codingPath: [CodingKey]
var count: Int = 0
var internalData: URLEncodedFormData = []
var childContainers: [Int: _Container] = [:]
private let configuration: URLEncodedFormEncoder.Configuration
func getData() throws -> URLEncodedFormData {
var result = self.internalData
for (key, childContainer) in self.childContainers {
result.children[String(key)] = try childContainer.getData()
}
switch self.configuration.arrayEncoding {
case .separator(let arraySeparator):
var valuesToImplode = result.values
result.values = []
if
case .bracket = self.configuration.arrayEncoding,
let emptyStringChild = self.internalData.children[""]
{
valuesToImplode = valuesToImplode + emptyStringChild.values
result.children[""]?.values = []
}
let implodedValue = try valuesToImplode.map({ (value: URLQueryFragment) -> String in
return try value.asUrlEncoded()
}).joined(separator: String(arraySeparator))
result.values = [.urlEncoded(implodedValue)]
case .bracket, .values:
break
}
return result
}
init(
codingPath: [CodingKey],
configuration: URLEncodedFormEncoder.Configuration
) {
self.codingPath = codingPath
self.configuration = configuration
}
func encodeNil() throws {
// skip
}
func encode<T>(_ value: T) throws where T: Encodable {
defer { self.count += 1 }
if let convertible = value as? URLQueryFragmentConvertible {
let value = convertible.urlQueryFragmentValue
switch self.configuration.arrayEncoding {
case .bracket:
var emptyStringChild = self.internalData.children[""] ?? []
emptyStringChild.values.append(value)
self.internalData.children[""] = emptyStringChild
case .separator, .values:
self.internalData.values.append(value)
}
} else {
let encoder = _Encoder(codingPath: codingPath, configuration: configuration)
try value.encode(to: encoder)
let childData = try encoder.getData()
if childData.hasOnlyValues {
switch self.configuration.arrayEncoding {
case .bracket:
var emptyStringChild = self.internalData.children[""] ?? []
emptyStringChild.values.append(contentsOf: childData.values)
self.internalData.children[""] = emptyStringChild
case .separator, .values:
self.internalData.values.append(contentsOf: childData.values)
}
} else {
self.internalData.children[count.description] = try encoder.getData()
}
}
}
/// See UnkeyedEncodingContainer.nestedContainer
func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey>
where NestedKey: CodingKey
{
defer { count += 1 }
let container = KeyedContainer<NestedKey>(
codingPath: self.codingPath,
configuration: self.configuration
)
self.childContainers[self.count] = container
return .init(container)
}
/// See UnkeyedEncodingContainer.nestedUnkeyedContainer
func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
defer { count += 1 }
let container = UnkeyedContainer(
codingPath: self.codingPath,
configuration: self.configuration
)
self.childContainers[count] = container
return container
}
/// See UnkeyedEncodingContainer.superEncoder
func superEncoder() -> Encoder {
fatalError()
}
}
/// Private `SingleValueEncodingContainer`.
private final class SingleValueContainer: SingleValueEncodingContainer, _Container {
/// See `SingleValueEncodingContainer`
var codingPath: [CodingKey]
func getData() throws -> URLEncodedFormData {
return data
}
/// The data being encoded
var data: URLEncodedFormData = []
private let configuration: URLEncodedFormEncoder.Configuration
/// Creates a new single value encoder
init(
codingPath: [CodingKey],
configuration: URLEncodedFormEncoder.Configuration
) {
self.codingPath = codingPath
self.configuration = configuration
}
/// See `SingleValueEncodingContainer`
func encodeNil() throws {
// skip
}
/// See `SingleValueEncodingContainer`
func encode<T>(_ value: T) throws where T: Encodable {
if let convertible = value as? URLQueryFragmentConvertible {
self.data.values.append(convertible.urlQueryFragmentValue)
} else {
let encoder = _Encoder(codingPath: self.codingPath, configuration: self.configuration)
try value.encode(to: encoder)
self.data = try encoder.getData()
}
}
}
}
private extension EncodingError {
static func invalidValue(_ value: Any, at path: [CodingKey]) -> EncodingError {
let pathString = path.map { $0.stringValue }.joined(separator: ".")
let context = EncodingError.Context(
codingPath: path,
debugDescription: "Invalid value at '\(pathString)': \(value)"
)
return Swift.EncodingError.invalidValue(value, context)
}
}