-
Notifications
You must be signed in to change notification settings - Fork 6
Middleware
Yuki Takei edited this page Oct 10, 2016
·
2 revisions
Middleware is functions that have access to the http request, the http response, and the next function in the application' s request-response cycle.
-
case respond(Response)
: Respond to the content immediately with givenResponse
-
case next(Request, Response)
: Chain to the next middleware or the route. -
case error(Error)
: Abort the middleware chain and pass the error toapp.catch
Handler.
You can choose 2 types of middleware registration ways from handy or creating Middleware struct.
app.use { request, response, responder in
do {
if let data = try File.synchronousRead("/path/to/file") {
response.data(data)
responder(.respond(response)) // respond to the read file content
} else {
responder(.next(request, response)) // Chaining to the next middleware or route
}
} catch {
responder(.error(error)) // Go to `catch` handler
}
}
struct FooMiddleware: Middleware {
func respond(_ request: Request, _ response: Response, _ responder: @escaping (Chainer) -> Void) {
do {
if let data = try File.synchronousRead("/path/to/file") {
response.data(data)
responder(.respond(response))
} else {
responder(.next(request, response))
}
} catch {
responder(.error(error))
}
}
}
app.use(FooMiddleware())