ParameterEncoder.swift 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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 { return 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. /// A `ParameterEncoder` that encodes types as URL-encoded query strings to be set on the URL or as body data, depending
  82. /// on the `Destination` set.
  83. ///
  84. /// If no `Content-Type` header is already set on the provided `URLRequest`s, it will be set to
  85. /// `application/x-www-form-urlencoded; charset=utf-8`.
  86. ///
  87. /// Encoding behavior can be customized by passing an instance of `URLEncodedFormEncoder` to the initializer.
  88. open class URLEncodedFormParameterEncoder: ParameterEncoder {
  89. /// Defines where the URL-encoded string should be set for each `URLRequest`.
  90. public enum Destination {
  91. /// Applies the encoded query string to any existing query string for `.get`, `.head`, and `.delete` request.
  92. /// Sets it to the `httpBody` for all other methods.
  93. case methodDependent
  94. /// Applies the encoded query string to any existing query string from the `URLRequest`.
  95. case queryString
  96. /// Applies the encoded query string to the `httpBody` of the `URLRequest`.
  97. case httpBody
  98. /// Determines whether the URL-encoded string should be applied to the `URLRequest`'s `url`.
  99. ///
  100. /// - Parameter method: The `HTTPMethod`.
  101. ///
  102. /// - Returns: Whether the URL-encoded string should be applied to a `URL`.
  103. func encodesParametersInURL(for method: HTTPMethod) -> Bool {
  104. switch self {
  105. case .methodDependent: return [.get, .head, .delete].contains(method)
  106. case .queryString: return true
  107. case .httpBody: return false
  108. }
  109. }
  110. }
  111. /// Returns an encoder with default parameters.
  112. public static var `default`: URLEncodedFormParameterEncoder { return URLEncodedFormParameterEncoder() }
  113. /// The `URLEncodedFormEncoder` to use.
  114. public let encoder: URLEncodedFormEncoder
  115. /// The `Destination` for the URL-encoded string.
  116. public let destination: Destination
  117. /// Creates an instance with the provided `URLEncodedFormEncoder` instance and `Destination` value.
  118. ///
  119. /// - Parameters:
  120. /// - encoder: The `URLEncodedFormEncoder`. `URLEncodedFormEncoder()` by default.
  121. /// - destination: The `Destination`. `.methodDependent` by default.
  122. public init(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(), destination: Destination = .methodDependent) {
  123. self.encoder = encoder
  124. self.destination = destination
  125. }
  126. open func encode<Parameters: Encodable>(_ parameters: Parameters?,
  127. into request: URLRequest) throws -> URLRequest {
  128. guard let parameters = parameters else { return request }
  129. var request = request
  130. guard let url = request.url else {
  131. throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url))
  132. }
  133. guard let method = request.method else {
  134. let rawValue = request.method?.rawValue ?? "nil"
  135. throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.httpMethod(rawValue: rawValue)))
  136. }
  137. if destination.encodesParametersInURL(for: method),
  138. var components = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  139. let query: String = try Result<String, Error> { try encoder.encode(parameters) }
  140. .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get()
  141. let newQueryString = [components.percentEncodedQuery, query].compactMap { $0 }.joinedWithAmpersands()
  142. components.percentEncodedQuery = newQueryString.isEmpty ? nil : newQueryString
  143. guard let newURL = components.url else {
  144. throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url))
  145. }
  146. request.url = newURL
  147. } else {
  148. if request.headers["Content-Type"] == nil {
  149. request.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8"))
  150. }
  151. request.httpBody = try Result<Data, Error> { try encoder.encode(parameters) }
  152. .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get()
  153. }
  154. return request
  155. }
  156. }