Skip to content

Middleware

Josh Wright edited this page Jan 14, 2021 · 4 revisions

Middleware

A Middleware is used to intercept either incoming Requests or outgoing Responses. Using futures, they can do something with those, either synchronously or asynchronously.

public protocol Middleware

Usage:

// Example synchronous middleware
struct SyncMiddleware: Middleware {
    func intercept(_ request: Request, next: @escaping Next) throws -> EventLoopFuture<Response>
        ... // Do something with `request`.
        // Then continue the chain. Could hook into this future to
        // do something with the `Response`.
        return next(request)
    }
}

// Example asynchronous middleware
struct AsyncMiddleware: Middleware {
    func intercept(_ request: Request, next: @escaping Next) throws -> EventLoopFuture<Response>
        // Run some async operation
        Services.db
            .runRawQuery(...)
            .flatMap { someData in
                // Set some data on the request for access in
                // subsequent Middleware or request handlers.
                // See `HTTPRequst.set` for more detail.
                request.set(someData)
                return next(request)
            }
    }
}

Requirements

intercept(_:​next:​)

Intercept a requst, returning a future with a Response representing the result of the subsequent handlers.

func intercept(_ request: Request, next: @escaping Next) throws -> EventLoopFuture<Response>

Be sure to call next when returning, unless you don't want the request to be handled.

Parameters

  • request: The incoming request to intercept, then pass along the handler chain.

Throws

Any error encountered when intercepting the request.

Alchemy
Types
Protocols
Global Typealiases
Global Variables
Global Functions
Fusion
Types
Protocols
Papyrus
Types
Protocols
Clone this wiki locally