Skip to content

Conforms `Request.Body` to `AsyncSequence`

Compare
Choose a tag to compare
@VaporBot VaporBot released this 03 Nov 16:46
· 147 commits to main since this release
699e4d6
This patch was authored by @mcritz and released by @0xTim.

This PR wraps Request.Body.drain() as a modern Swift AsyncSequence<ByteBuffer, Error>.

This is useful to stream bytes from request rather than collecting them in memory. Example: A route could handle a multigigbyte file upload like this:

do {
    let nioFileHandle = try NIOFileHandle(path: filePath, mode: .write)
    var offset: Int64 = 0
    
    for try await bytes in req.body {
        try await req.application.fileio.write(fileHandle: nioFileHandle,
                                               toOffset: offset,
                                               buffer: bytes,
                                               eventLoop: req.eventLoop).get()
        offset += Int64(bytes.readableBytes)
        try nioFileHandle.close()
    }
} catch {
   ...
}