Skip to content

Commit e1bba70

Browse files
authored
Multi-part Form Support (#19)
1 parent 029e800 commit e1bba70

File tree

6 files changed

+786
-2
lines changed

6 files changed

+786
-2
lines changed

Sources/Endpoints/Endpoint+URLRequest.swift

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,14 +125,23 @@ extension Endpoint {
125125
urlRequest.url = url
126126

127127
if !(body is EmptyCodable) {
128+
let encoder = Self.bodyEncoder
128129
do {
129-
urlRequest.httpBody = try Self.bodyEncoder.encode(body)
130+
urlRequest.httpBody = try encoder.encode(body)
130131
} catch {
131132
throw EndpointError.invalidBody(error)
132133
}
133134

134135
if headerItems[Header.contentType.name] == nil {
135-
urlRequest.addValue("application/json", forHTTPHeaderField: Header.contentType.name)
136+
let encoderType = type(of: encoder)
137+
if let contentType = encoderType.contentType {
138+
if contentType.lowercased().hasPrefix("multipart/form-data"),
139+
let multipartEncoder = encoder as? MultipartFormEncoder {
140+
urlRequest.addValue(multipartEncoder.contentType, forHTTPHeaderField: Header.contentType.name)
141+
} else {
142+
urlRequest.addValue(contentType, forHTTPHeaderField: Header.contentType.name)
143+
}
144+
}
136145
}
137146
} else if !bodyFormItems.isEmpty {
138147
urlRequest.httpBody = bodyFormItems.formString.data(using: .utf8)

Sources/Endpoints/Endpoint.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,20 @@ public enum HeaderField<T> {
3636
public struct EmptyCodable: Codable { }
3737

3838
public protocol EncoderType {
39+
static var contentType: String? { get }
3940
func encode<T: Encodable>(_ value: T) throws -> Data
4041
}
4142

43+
public extension EncoderType {
44+
static var contentType: String? { nil }
45+
}
46+
4247
extension JSONEncoder: EncoderType { }
4348

49+
extension JSONEncoder {
50+
public static var contentType: String? { "application/json" }
51+
}
52+
4453
public protocol DecoderType {
4554
func decode<T: Decodable>(_ type: T.Type, from data: Data) throws -> T
4655
}

0 commit comments

Comments
 (0)