Skip to main content

rok_db_core/
web.rs

1//! Web integration: serde support (feature `serde`) and axum responses
2//! (feature `axum`).
3//!
4//! With `axum`, handlers can return `rok_db::Result<T>` (or use `?` on rok-db
5//! calls) and errors become JSON responses:
6//!
7//! | error | status | `error` code |
8//! |---|---|---|
9//! | `NotFound` | 404 | `not_found` |
10//! | `Validation` | 422 | `validation_failed` (with `fields`) |
11//! | `Hook` | 422 | `rejected` |
12//! | foreign-key violation | 422 | `invalid_reference` |
13//! | `Conflict` | 409 | `conflict` |
14//! | unique violation | 409 | `already_exists` |
15//! | `InvalidCursor` | 400 | `invalid_cursor` |
16//! | anything else | 500 | `internal_error` (details are logged, not returned) |
17//!
18//! ```ignore
19//! async fn show(State(db): State<Db>, Path(id): Path<i64>) -> rok_db::Result<Json<User>> {
20//!     Ok(Json(User::find_or_fail(&db, id).await?))
21//! }
22//! ```
23
24#[cfg(feature = "serde")]
25mod serde_impls {
26    use serde::ser::SerializeStruct;
27    use serde::{Deserialize, Deserializer, Serialize, Serializer};
28
29    use crate::validate::{FieldError, ValidationErrors};
30    use crate::{Cursor, CursorPage, Page};
31
32    /// `{"items": […], "total", "page", "per_page", "total_pages"}`
33    impl<T: Serialize> Serialize for Page<T> {
34        fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
35            let mut st = s.serialize_struct("Page", 5)?;
36            st.serialize_field("items", &self.items)?;
37            st.serialize_field("total", &self.total)?;
38            st.serialize_field("page", &self.page)?;
39            st.serialize_field("per_page", &self.per_page)?;
40            st.serialize_field("total_pages", &self.total_pages())?;
41            st.end()
42        }
43    }
44
45    /// `{"items": […], "next": "<cursor>" | null}`
46    impl<T: Serialize> Serialize for CursorPage<T> {
47        fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
48            let mut st = s.serialize_struct("CursorPage", 2)?;
49            st.serialize_field("items", &self.items)?;
50            st.serialize_field("next", &self.next)?;
51            st.end()
52        }
53    }
54
55    /// Serialized as its opaque string form.
56    impl Serialize for Cursor {
57        fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
58            s.collect_str(self)
59        }
60    }
61
62    /// Parsed from its string form, e.g. a `?after=` query parameter.
63    impl<'de> Deserialize<'de> for Cursor {
64        fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
65            let s = String::deserialize(d)?;
66            s.parse().map_err(serde::de::Error::custom)
67        }
68    }
69
70    impl Serialize for FieldError {
71        fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
72            let mut st = s.serialize_struct("FieldError", 3)?;
73            st.serialize_field("field", self.field)?;
74            st.serialize_field("code", self.code)?;
75            st.serialize_field("message", &self.message)?;
76            st.end()
77        }
78    }
79
80    /// A list of `{"field", "code", "message"}`.
81    impl Serialize for ValidationErrors {
82        fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
83            self.errors().serialize(s)
84        }
85    }
86}
87
88#[cfg(feature = "axum")]
89mod axum_impls {
90    use axum_core::body::Body;
91    use axum_core::response::{IntoResponse, Response};
92    use http::{StatusCode, header};
93
94    use crate::Error;
95
96    impl Error {
97        /// The HTTP status and machine-readable code this error maps to.
98        pub fn http_status(&self) -> (StatusCode, &'static str) {
99            match self {
100                Error::NotFound { .. } => (StatusCode::NOT_FOUND, "not_found"),
101                Error::Validation(_) => (StatusCode::UNPROCESSABLE_ENTITY, "validation_failed"),
102                Error::Hook(_) => (StatusCode::UNPROCESSABLE_ENTITY, "rejected"),
103                Error::Conflict { .. } => (StatusCode::CONFLICT, "conflict"),
104                Error::InvalidCursor(_) => (StatusCode::BAD_REQUEST, "invalid_cursor"),
105                e if e.is_not_found() => (StatusCode::NOT_FOUND, "not_found"),
106                e if e.is_unique_violation() => (StatusCode::CONFLICT, "already_exists"),
107                e if e.is_foreign_key_violation() => {
108                    (StatusCode::UNPROCESSABLE_ENTITY, "invalid_reference")
109                }
110                _ => (StatusCode::INTERNAL_SERVER_ERROR, "internal_error"),
111            }
112        }
113    }
114
115    impl IntoResponse for Error {
116        fn into_response(self) -> Response {
117            let (status, code) = self.http_status();
118            let message = match code {
119                "internal_error" => {
120                    tracing::error!(target: "rok_db::http", error = %self, "internal error");
121                    "internal server error".to_owned()
122                }
123                "already_exists" => "a record with these values already exists".to_owned(),
124                "invalid_reference" => "a referenced record does not exist".to_owned(),
125                _ => self.to_string(),
126            };
127            let mut body = serde_json::json!({ "error": code, "message": message });
128            if let Error::Validation(errors) = &self {
129                body["fields"] = serde_json::to_value(errors).unwrap_or_default();
130            }
131            let mut response = Response::new(Body::from(body.to_string()));
132            *response.status_mut() = status;
133            response.headers_mut().insert(
134                header::CONTENT_TYPE,
135                header::HeaderValue::from_static("application/json"),
136            );
137            response
138        }
139    }
140}