TypeSafeMiddleware

public protocol TypeSafeMiddleware

The protocol that type-safe middleware must implement to be used in Kitura Codable routes.

Classes or structs conforming to TypeSafeMiddleware must contain a static handle function that processes an incoming request. On success, the handle function creates an instance of Self and passes this instance to the users route handler.

Usage Example:

In this example, a UserMiddleware struct is defined that checks the request for the header “TestHeader”. If the header is found UserMiddleware initialises itself with the header and passes itself to the route. If the header is not found it returns a RequestError.

struct UserMiddleware: TypeSafeMiddleware {
    let header: String

    static func handle(
                request: RouterRequest,
                response: RouterResponse,
                completion: @escaping (UserMiddleware?, RequestError?) -> Void
    ) {
        guard let expectedHeader = request.headers["TestHeader"] else {
            return completion(nil, .badRequest)
        }
        let selfInstance: UserMiddleware = UserMiddleware(header: expectedHeader)
        completion(selfInstance, nil)
    }
}
  • Handle an incoming HTTP request.

    Declaration

    Swift

    static func handle(request: RouterRequest, response: RouterResponse, completion: @escaping (Self?, RequestError?) -> Void)

    Parameters

    request

    The RouterRequest object used to work with the incoming HTTP request.

    response

    The RouterResponse object used to respond to the HTTP request.

    completion

    The closure to invoke once middleware processing is complete. Either an instance of Self or a RequestError should be provided, indicating a successful or failed attempt to process the request, respectively.