Skip to main content

autapi/response/
mod.rs

1mod json;
2mod status_codes;
3mod text;
4mod undocumented;
5
6use std::convert::Infallible;
7
8pub use self::{json::*, status_codes::*, text::*};
9use crate::{Registry, openapi::Responses};
10
11pub type Response = axum::response::Response;
12
13/// A type that is convertible to an HTTP response with OpenAPI description.
14///
15/// Most notably, this trait is implemented for
16/// - `T: ToSchema + SchemaSerialize`, returning a `200 Ok` response with
17///   `Content-Type: application/json`
18/// - `Result<T, E>` with `T: IntoResponse` and `E: IntoResponse`
19/// - The new-type structs in this module named after status codes (e.g. [`Created`])
20pub trait IntoResponse {
21    /// Describes the responses generated via the [`into_response`](Self::into_response) function.
22    fn openapi(registry: &mut Registry) -> Responses;
23    /// Converts this value into an axum response.
24    fn into_response(self) -> Response;
25}
26
27impl<T: IntoResponse, E: IntoResponse> IntoResponse for Result<T, E> {
28    fn openapi(registry: &mut Registry) -> Responses {
29        let mut responses = T::openapi(registry);
30        responses.merge_with(E::openapi(registry));
31        responses
32    }
33
34    fn into_response(self) -> Response {
35        match self {
36            Self::Ok(t) => t.into_response(),
37            Self::Err(e) => e.into_response(),
38        }
39    }
40}
41
42impl IntoResponse for Infallible {
43    fn openapi(_: &mut Registry) -> Responses {
44        Default::default()
45    }
46    fn into_response(self) -> Response {
47        match self {}
48    }
49}