ParameterEncoder.swift 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. //
  2. // ParameterEncoder.swift
  3. //
  4. // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// A type that can encode any `Encodable` type into a `URLRequest`.
  26. public protocol ParameterEncoder {
  27. /// Encode the provided `Encodable` parameters into `request`.
  28. ///
  29. /// - Parameters:
  30. /// - parameters: The `Encodable` parameter value.
  31. /// - request: The `URLRequest` into which to encode the parameters.
  32. ///
  33. /// - Returns: A `URLRequest` with the result of the encoding.
  34. /// - Throws: An `Error` when encoding fails. For Alamofire provided encoders, this will be an instance of
  35. /// `AFError.parameterEncoderFailed` with an associated `ParameterEncoderFailureReason`.
  36. func encode<Parameters: Encodable>(_ parameters: Parameters?, into request: URLRequest) throws -> URLRequest
  37. }
  38. /// A `ParameterEncoder` that encodes types as JSON body data.
  39. ///
  40. /// If no `Content-Type` header is already set on the provided `URLRequest`s, it's set to `application/json`.
  41. open class JSONParameterEncoder: ParameterEncoder {
  42. /// Returns an encoder with default parameters.
  43. public static var `default`: JSONParameterEncoder { JSONParameterEncoder() }
  44. /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.prettyPrinted`.
  45. public static var prettyPrinted: JSONParameterEncoder {
  46. let encoder = JSONEncoder()
  47. encoder.outputFormatting = .prettyPrinted
  48. return JSONParameterEncoder(encoder: encoder)
  49. }
  50. /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.sortedKeys`.
  51. @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  52. public static var sortedKeys: JSONParameterEncoder {
  53. let encoder = JSONEncoder()
  54. encoder.outputFormatting = .sortedKeys
  55. return JSONParameterEncoder(encoder: encoder)
  56. }
  57. /// `JSONEncoder` used to encode parameters.
  58. public let encoder: JSONEncoder
  59. /// Creates an instance with the provided `JSONEncoder`.
  60. ///
  61. /// - Parameter encoder: The `JSONEncoder`. `JSONEncoder()` by default.
  62. public init(encoder: JSONEncoder = JSONEncoder()) {
  63. self.encoder = encoder
  64. }
  65. open func encode<Parameters: Encodable>(_ parameters: Parameters?,
  66. into request: URLRequest) throws -> URLRequest {
  67. guard let parameters = parameters else { return request }
  68. var request = request
  69. do {
  70. let data = try encoder.encode(parameters)
  71. request.httpBody = data
  72. if request.headers["Content-Type"] == nil {
  73. request.headers.update(.contentType("application/json"))
  74. }
  75. } catch {
  76. throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
  77. }
  78. return request
  79. }
  80. }
  81. extension ParameterEncoder where Self == JSONParameterEncoder {
  82. /// Provides a default `JSONParameterEncoder` instance.
  83. public static var json: JSONParameterEncoder { JSONParameterEncoder() }
  84. /// Creates a `JSONParameterEncoder` using the provided `JSONEncoder`.
  85. ///
  86. /// - Parameter encoder: `JSONEncoder` used to encode parameters. `JSONEncoder()` by default.
  87. /// - Returns: The `JSONParameterEncoder`.
  88. public static func json(encoder: JSONEncoder = JSONEncoder()) -> JSONParameterEncoder {
  89. JSONParameterEncoder(encoder: encoder)
  90. }
  91. }
  92. /// A `ParameterEncoder` that encodes types as URL-encoded query strings to be set on the URL or as body data, depending
  93. /// on the `Destination` set.
  94. ///
  95. /// If no `Content-Type` header is already set on the provided `URLRequest`s, it will be set to
  96. /// `application/x-www-form-urlencoded; charset=utf-8`.
  97. ///
  98. /// Encoding behavior can be customized by passing an instance of `URLEncodedFormEncoder` to the initializer.
  99. open class URLEncodedFormParameterEncoder: ParameterEncoder {
  100. /// Defines where the URL-encoded string should be set for each `URLRequest`.
  101. public enum Destination {
  102. /// Applies the encoded query string to any existing query string for `.get`, `.head`, and `.delete` request.
  103. /// Sets it to the `httpBody` for all other methods.
  104. case methodDependent
  105. /// Applies the encoded query string to any existing query string from the `URLRequest`.
  106. case queryString
  107. /// Applies the encoded query string to the `httpBody` of the `URLRequest`.
  108. case httpBody
  109. /// Determines whether the URL-encoded string should be applied to the `URLRequest`'s `url`.
  110. ///
  111. /// - Parameter method: The `HTTPMethod`.
  112. ///
  113. /// - Returns: Whether the URL-encoded string should be applied to a `URL`.
  114. func encodesParametersInURL(for method: HTTPMethod) -> Bool {
  115. switch self {
  116. case .methodDependent: return [.get, .head, .delete].contains(method)
  117. case .queryString: return true
  118. case .httpBody: return false
  119. }
  120. }
  121. }
  122. /// Returns an encoder with default parameters.
  123. public static var `default`: URLEncodedFormParameterEncoder { URLEncodedFormParameterEncoder() }
  124. /// The `URLEncodedFormEncoder` to use.
  125. public let encoder: URLEncodedFormEncoder
  126. /// The `Destination` for the URL-encoded string.
  127. public let destination: Destination
  128. /// Creates an instance with the provided `URLEncodedFormEncoder` instance and `Destination` value.
  129. ///
  130. /// - Parameters:
  131. /// - encoder: The `URLEncodedFormEncoder`. `URLEncodedFormEncoder()` by default.
  132. /// - destination: The `Destination`. `.methodDependent` by default.
  133. public init(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(), destination: Destination = .methodDependent) {
  134. self.encoder = encoder
  135. self.destination = destination
  136. }
  137. open func encode<Parameters: Encodable>(_ parameters: Parameters?,
  138. into request: URLRequest) throws -> URLRequest {
  139. guard let parameters = parameters else { return request }
  140. var request = request
  141. guard let url = request.url else {
  142. throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url))
  143. }
  144. guard let method = request.method else {
  145. let rawValue = request.method?.rawValue ?? "nil"
  146. throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.httpMethod(rawValue: rawValue)))
  147. }
  148. if destination.encodesParametersInURL(for: method),
  149. var components = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  150. let query: String = try Result<String, Error> { try encoder.encode(parameters) }
  151. .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get()
  152. let newQueryString = [components.percentEncodedQuery, query].compactMap { $0 }.joinedWithAmpersands()
  153. components.percentEncodedQuery = newQueryString.isEmpty ? nil : newQueryString
  154. guard let newURL = components.url else {
  155. throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url))
  156. }
  157. request.url = newURL
  158. } else {
  159. if request.headers["Content-Type"] == nil {
  160. request.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8"))
  161. }
  162. request.httpBody = try Result<Data, Error> { try encoder.encode(parameters) }
  163. .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get()
  164. }
  165. return request
  166. }
  167. }
  168. extension ParameterEncoder where Self == URLEncodedFormParameterEncoder {
  169. /// Provides a default `URLEncodedFormParameterEncoder` instance.
  170. public static var urlEncodedForm: URLEncodedFormParameterEncoder { URLEncodedFormParameterEncoder() }
  171. /// Creates a `URLEncodedFormParameterEncoder` with the provided encoder and destination.
  172. ///
  173. /// - Parameters:
  174. /// - encoder: `URLEncodedFormEncoder` used to encode the parameters. `URLEncodedFormEncoder()` by default.
  175. /// - destination: `Destination` to which to encode the parameters. `.methodDependent` by default.
  176. /// - Returns: The `URLEncodedFormParameterEncoder`.
  177. public static func urlEncodedForm(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(),
  178. destination: URLEncodedFormParameterEncoder.Destination = .methodDependent) -> URLEncodedFormParameterEncoder {
  179. URLEncodedFormParameterEncoder(encoder: encoder, destination: destination)
  180. }
  181. }