Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions Sources/Endpoints/Endpoint+URLRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -125,14 +125,23 @@ extension Endpoint {
urlRequest.url = url

if !(body is EmptyCodable) {
let encoder = Self.bodyEncoder
do {
urlRequest.httpBody = try Self.bodyEncoder.encode(body)
urlRequest.httpBody = try encoder.encode(body)
} catch {
throw EndpointError.invalidBody(error)
}

if headerItems[Header.contentType.name] == nil {
urlRequest.addValue("application/json", forHTTPHeaderField: Header.contentType.name)
let encoderType = type(of: encoder)
if let contentType = encoderType.contentType {
if contentType.lowercased().hasPrefix("multipart/form-data"),
let multipartEncoder = encoder as? MultipartFormEncoder {
urlRequest.addValue(multipartEncoder.contentType, forHTTPHeaderField: Header.contentType.name)
} else {
urlRequest.addValue(contentType, forHTTPHeaderField: Header.contentType.name)
}
}
}
} else if !bodyFormItems.isEmpty {
urlRequest.httpBody = bodyFormItems.formString.data(using: .utf8)
Expand Down
9 changes: 9 additions & 0 deletions Sources/Endpoints/Endpoint.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,20 @@ public enum HeaderField<T> {
public struct EmptyCodable: Codable { }

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

public extension EncoderType {
static var contentType: String? { nil }
}

extension JSONEncoder: EncoderType { }

extension JSONEncoder {
public static var contentType: String? { "application/json" }
}

public protocol DecoderType {
func decode<T: Decodable>(_ type: T.Type, from data: Data) throws -> T
}
Expand Down
Loading