HTTPMessageDecoder

public protocol HTTPMessageDecoder

Capable of decoding a Decodable type from an HTTPBody.

HTTPMessageDecoders must handle all cases of an HTTPBody, including streaming bodies. Because the HTTPBody may be streaming (async), the decode(_:from:on:) method returns a Future.

let jsonDecoder: BodyDecoder = JSONDecoder()
let string = try jsonDecoder.decode(String.self, from: HTTPBody(string: "hello"), on: ...).wait()
print(string) /// "hello" from the HTTP body

The HTTPMessageDecoder protocol is what powers the ContentContainers on Request and Response.

let string = try req.content.decode(String.self)
print(string) // Future<String>

HTTPMessageDecoders can be registered with ContentConfig during the application config phase. The decoders are associated with a MediaType when registered. When decoding content, the HTTP message’s MediaType is used to lookup an appropriate coder.

var contentConfig = ContentConfig.default()
contentConfig.use(decoder: JSONDecoder(), for: .json)
services.register(contentConfig)
  • Decodes the supplied Decodable type from an HTTPMessage.

    let jsonDecoder: BodyDecoder = JSONDecoder()
    let string = try jsonDecoder.decode(String.self, from: httpReq, on: ...).wait()
    print(string) /// "hello" from the HTTP body
    

    Throws

    Any errors that may have occurred while decoding the HTTPMessage.

    Declaration

    Swift

    func decode<D, M>(_ decodable: D.Type, from message: M, maxSize: Int, on worker: Worker) throws -> Future<D> where D : Decodable, M : HTTPMessage

    Parameters

    decodable

    Decodable type to decode from the HTTPBody.

    from

    HTTPMessage to decode the Decodable type from. The HTTPBody may be static or streaming.

    maxSize

    Maximum size in bytes for streaming bodies.

    on

    Worker to perform asynchronous tasks on.

    Return Value

    Future containing the decoded type.