responseFrom function
Turns whatever a typed handler returned into a response.
The rule is the one axum uses for IntoResponse: the handler says what it
produced, and the runtime decides how it reaches the wire. That is what
lets a handler end in repository.find(id) rather than in a call to an
encoder.
| Returned | Answer |
|---|---|
Response |
itself, untouched |
IntoResponse |
intoResponse(), which covers Rejection |
Ok(value) |
the value, dispatched again |
Err(error) |
the error, dispatched again, defaulting to 500 |
Some(value) |
the value, dispatched again |
None |
404 |
null |
204 |
String |
text/plain, sent as written |
Stream<List<int>> |
streamed as it arrives, unbuffered |
| anything else | JSON, through serialize when it derives Serialize |
A bare String is text, not JSON — axum's rule. To send a JSON string
specifically, wrap it in a list or a map, or call jsonResponse.
status applies only to the last row and to Ok, so a create can answer
201 without the failure path inheriting it.
Implementation
Response responseFrom(Object? value, {int status = 200}) {
return switch (value) {
null => noContent(),
final Response response => response,
final IntoResponse into => into.intoResponse(),
Ok(value: final inner) => responseFrom(inner, status: status),
Err(error: final inner) => _errorResponse(inner),
Some(value: final inner) => responseFrom(inner, status: status),
None() => const Rejection.notFound('not found').intoResponse(),
final String text => textResponse(text, status: status),
final Stream<List<int>> body => streamed(body, status: status),
_ => jsonResponse(value, status: status),
};
}