Skip to content

Instantly share code, notes, and snippets.

@paulofaria
Last active January 7, 2016 15:58
Show Gist options
  • Save paulofaria/c330e028af8c56f21a4e to your computer and use it in GitHub Desktop.
Save paulofaria/c330e028af8c56f21a4e to your computer and use it in GitHub Desktop.
protocol MiddlewareType {
func intercept(request: Request, nextResponder: ResponderType) throws -> Response
}
protocol RequestMiddlewareType: MiddlewareType {
func intercept(request: Request) throws -> Request
}
extension RequestMiddlewareType {
func intercept(request: Request, nextResponder: ResponderType) throws -> Response {
let interceptedRequest = try self.intercept(request)
return try nextResponder.respond(request)
}
}
protocol ResponseMiddlewareType: MiddlewareType {
func intercept(response: Response) throws -> Response
}
extension ResponseMiddlewareType {
func intercept(request: Request, nextResponder: ResponderType) throws -> Response {
let response = try nextResponder.respond(request)
return try self.intercept(response)
}
}
protocol FailureRecoveryMiddlewareType: MiddlewareType {
func intercept(error: ErrorType) -> Response
}
extension FailureRecoveryMiddlewareType {
func intercept(request: Request, nextResponder: ResponderType) throws -> Response {
do {
return try nextResponder.respond(request)
} catch {
return self.intercept(error)
}
}
}
enum EarlyReturnMiddlewareResult {
case PassForward(Request)
case EarlyReturn(Response)
}
protocol EarlyReturnMiddlewareType: MiddlewareType {
func intercept(request: Request) throws -> EarlyReturnMiddlewareResult
}
extension EarlyReturnMiddlewareType {
func intercept(request: Request, nextResponder: ResponderType) throws -> Response {
switch try self.intercept(request) {
case .PassForward(let request):
return try nextResponder.respond(request)
case .EarlyReturn(let response):
return response
}
}
}
@paulofaria
Copy link
Author

route.get("/", middleware: logger, errorHandler, authenticator, contentNegotiator, templateRender, responder: responder)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment