Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add HBRequest.collateBody #147

Merged
merged 2 commits into from
Nov 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Sources/Hummingbird/Server/Request.swift
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,17 @@ public struct HBRequest: HBExtensible {
return self.eventLoop.makeSucceededFuture(value)
}

// Return new version of request with collated request body. If you want to process the
// request body in middleware you need to call this to ensure you have the full request
// body. Once this is called the request generated by this should be passed to the nextResponder
public func collateBody() -> EventLoopFuture<HBRequest> {
self.body.consumeBody(on: self.eventLoop).flatMapThrowing { buffer in
var request = self
request.body = .byteBuffer(buffer)
return request
}
}

/// Store all the read-only values of the request in a class to avoid copying them
/// everytime we pass the `HBRequest` struct about
final class _Internal {
Expand Down
23 changes: 23 additions & 0 deletions Tests/HummingbirdTests/ApplicationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,29 @@ final class ApplicationTests: XCTestCase {
}
}

func testCollateBody() throws {
struct CollateMiddleware: HBMiddleware {
func apply(to request: HBRequest, next: HBResponder) -> EventLoopFuture<HBResponse> {
return request.collateBody().flatMap { request in
request.logger.info("Buffer size: \(request.body.buffer!.readableBytes)")
return next.respond(to: request)
}
}
}
let app = HBApplication(testing: .embedded)
app.middleware.add(CollateMiddleware())
app.router.put("/hello") { _ -> HTTPResponseStatus in
return .ok
}
try app.XCTStart()
defer { app.XCTStop() }

let buffer = self.randomBuffer(size: 512_000)
app.XCTExecute(uri: "/hello", method: .PUT, body: buffer) { response in
XCTAssertEqual(response.status, .ok)
}
}

func testOptional() throws {
let app = HBApplication(testing: .embedded)
app.router
Expand Down