Skip to content

Commit

Permalink
Merge pull request #10 from tonyarnold/handle-redirects
Browse files Browse the repository at this point in the history
Allow Abort.redirect(…) to pass through the middleware
  • Loading branch information
0xTim committed Sep 11, 2019
2 parents 9cf9e8d + f8c2249 commit 63dba34
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
17 changes: 16 additions & 1 deletion Sources/LeafErrorMiddleware/LeafErrorMiddleware.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,18 @@ public final class LeafErrorMiddleware: Middleware, Service {
}.catchFlatMap { error in
switch (error) {
case let abort as AbortError:
guard
abort.status.representsError
else {
if let location = abort.headers[.location].first {
return req.future(req.redirect(to: location))
} else {
return try self.handleError(for: req, status: abort.status)
}
}
return try self.handleError(for: req, status: abort.status)
default:
return try self.handleError(for: req, status: .internalServerError)
return try self.handleError(for: req, status: .internalServerError)
}
}
} catch {
Expand Down Expand Up @@ -82,3 +91,9 @@ extension HTTPStatus {
}
}
}

private extension HTTPResponseStatus {
var representsError: Bool {
return (HTTPResponseStatus.badRequest.code ... HTTPResponseStatus.networkAuthenticationRequired.code) ~= code
}
}
11 changes: 11 additions & 0 deletions Tests/LeafErrorMiddlewareTests/LeafErrorMiddlewareTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class LeafErrorMiddlewareTests: XCTestCase {
("testThatUnauthorisedIsPassedThroughToServerErrorPage", testThatUnauthorisedIsPassedThroughToServerErrorPage),
("testThatFuture404IsCaughtCorrectly", testThatFuture404IsCaughtCorrectly),
("testThatFuture403IsCaughtCorrectly", testThatFuture403IsCaughtCorrectly),
("testThatRedirectIsNotCaught", testThatRedirectIsNotCaught)
]

// MARK: - Properties
Expand Down Expand Up @@ -69,6 +70,10 @@ class LeafErrorMiddlewareTests: XCTestCase {
router.get("future403") { req -> Future<Response> in
return req.future(error: Abort(.forbidden))
}

router.get("future303") { req -> Future<Response> in
return req.future(error: Abort.redirect(to: "ok"))
}
}

let router = EngineRouter.default()
Expand Down Expand Up @@ -169,6 +174,12 @@ class LeafErrorMiddlewareTests: XCTestCase {
XCTAssertEqual(response.http.status, .forbidden)
XCTAssertEqual(viewRenderer.leafPath, "serverError")
}

func testThatRedirectIsNotCaught() throws {
let response = try app.getResponse(to: "/future303")
XCTAssertEqual(response.http.status, .seeOther)
XCTAssertEqual(response.http.headers[.location].first, "ok")
}
}

extension HTTPBody {
Expand Down

0 comments on commit 63dba34

Please sign in to comment.