Skip to content

You're viewing documentation for a pre-release version. View the latest stable version

Instance Method

collect(max:)

Reads the whole body into memory, running a streaming body to completion.
mutating func collect(max: BodySizeLimit = .default) async throws -> Data?

Parameters

max

The most bytes to buffer. A stream that produces more fails with Abort .contentTooLarge rather than growing without bound - a body arriving from somewhere else, such as a client response, is not bounded by anything this process controls. nil, the default, buffers whatever the body produces.

Return Value

The body’s bytes, or nil if the body is empty.

Discussion

Collecting a streaming body replaces it with the bytes it produced as a mutating operation. A stream’s closure can only be relied on to run once - it may be reading a file handle, or draining an AsyncSequence - so re-running it silently yields a short or empty body. Caching the result means anything further down the chain, including the server that serialises the response, sees an ordinary in-memory body instead.

The bytes are also cached in state shared with every copy of this body, so collecting through one copy is visible from the others. That matters where the collection cannot be written back - a ContentContainer reached through a computed content property holds a copy, so without the shared cache decoding a streaming body would drain it and leave the original pointing at a spent stream.

Use withStreamingBytes(_:) instead when the whole body is not genuinely needed in memory.

Throws

Abort with .contentTooLarge if a streaming body exceeds max.