BodyEncoder
public struct BodyEncoder<Body>
A generic value type to encode request body content as Data
Usage
You specilize the Encoder
with the type you want to encoder, and pass in a closure to convert the type into Data
let encoder = BodyEncoder<MyType> { body in
// return `Data?` or throw an error
}
Reusability
Typically, you will want to re-use body encoders for a given type.
The best way to do this is to declare a your encoder in a type-constrained extensions
extension BodyEncoder where Body == MyType {
static var myEncoder: Self {
.init { body in
// Convert `MyType?` into `Data?` or throw an error
}
}
}
// You can now use this encoder with a `ComposableRequest`, or when creating type that conform to `Requestable`
let request = ComposableRequest<Any, MyType, Error>
.encode(with: .myEncoder)
struct MyRequest: Requestable {
var requestEncoder: BodyEncoder<MyType> {
.myEncoder
}
}
Alternatively, if you want to create an encoder for a type you have control over, simply have that type conform toAutomaticBodyEncoding
.
A default
encoder is created for you automatically, and added by default to every Requestable
or ComposableRequest
type that has been specialized with your type as its RequestBody
extension MyType: AutomaticBodyEncoding {
func asData() throws -> Data? {
// Return `Data?` or throw an error
}
}
// `default` is created for you automatically, and need not be added to `Requestable` or `ComposableRequest` instances.
let encoder = BodyEncoder<MyType>.default
Ombi provides default body encoders for the following types:
String
Data
AnyJSON
RequestParameters
- Types that conform to
Encodable
- Types that conform to
AutomaticBodyEncoding
See similar types BodyDecoder
and ResponseValidator
-
Create a
BodyDecoder
Declaration
Swift
public init(_ handler: @escaping Handler)
Parameters
handler
The encoding closure
-
Closure used to encode
Body
toData
Declaration
Swift
public typealias Handler = (Body?) throws -> Data?
-
The handler that decodes
Body
Declaration
Swift
public let encode: Handler
-
Fatal encoder that will cause a runtime failure
Declaration
Swift
static var fatal: `Self` { get }
-
Create a
String
body encoder with a given encodingDeclaration
Swift
init(encoding: String.Encoding = .utf8)
Parameters
encoding
The string encoding to use
-
The default
String
encoderDeclaration
Swift
static var `default`: `Self` { get }
-
The default
data
encoderDeclaration
Swift
static var `default`: `Self` { get }
-
The default
RequestParameters
encoderDeclaration
Swift
static var `default`: `Self` { get }
-
Create an encoder for a
Codable
using aJSONEncoder
Declaration
Swift
static func json(encoder: JSONEncoder = JSONEncoder()) -> BodyEncoder<Body>
Parameters
encoder
The
JSONEncoder
to useReturn Value
The encoder
-
The default
Codable
encoderDeclaration
Swift
static var `default`: `Self` { get }
-
The default encoder for types that conform to
AutomaticBodyEncoding
Declaration
Swift
static var `default`: `Self` { get }