Skip to main content

larastvel_core/http/
mod.rs

1use axum::{
2    body::Body,
3    extract::Request as AxumRequest,
4    response::{IntoResponse, Response},
5    Json,
6};
7use serde::{Deserialize, Serialize};
8
9pub type Request = AxumRequest<Body>;
10
11#[derive(Debug, Serialize, Deserialize)]
12pub struct JsonResponse<T: Serialize> {
13    pub data: T,
14    pub message: Option<String>,
15}
16
17impl<T: Serialize> JsonResponse<T> {
18    pub fn new(data: T) -> Self {
19        Self {
20            data,
21            message: None,
22        }
23    }
24
25    pub fn with_message(mut self, msg: &str) -> Self {
26        self.message = Some(msg.to_string());
27        self
28    }
29}
30
31impl<T: Serialize> IntoResponse for JsonResponse<T> {
32    fn into_response(self) -> Response {
33        Json(serde_json::json!({
34            "data": self.data,
35            "message": self.message,
36        }))
37        .into_response()
38    }
39}
40
41pub type LarastvelResult<T> = Result<T, Error>;
42
43#[derive(Debug, thiserror::Error)]
44pub enum Error {
45    #[error("Not Found: {0}")]
46    NotFound(String),
47    #[error("Validation Error: {0}")]
48    Validation(String),
49    #[error("Internal Error: {0}")]
50    Internal(String),
51    #[error("Unauthorized: {0}")]
52    Unauthorized(String),
53}
54
55impl IntoResponse for Error {
56    fn into_response(self) -> Response {
57        let (status, message) = match &self {
58            Error::NotFound(msg) => (axum::http::StatusCode::NOT_FOUND, msg.clone()),
59            Error::Validation(msg) => (axum::http::StatusCode::UNPROCESSABLE_ENTITY, msg.clone()),
60            Error::Internal(msg) => {
61                tracing::error!("Internal error: {}", msg);
62                (axum::http::StatusCode::INTERNAL_SERVER_ERROR, msg.clone())
63            }
64            Error::Unauthorized(msg) => (axum::http::StatusCode::UNAUTHORIZED, msg.clone()),
65        };
66
67        (status, Json(serde_json::json!({"error": message}))).into_response()
68    }
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74    use axum::http::StatusCode;
75
76    #[test]
77    fn test_json_response_new() {
78        let resp = JsonResponse::new("hello");
79        assert_eq!(resp.data, "hello");
80        assert!(resp.message.is_none());
81    }
82
83    #[test]
84    fn test_json_response_with_message() {
85        let resp = JsonResponse::new(42).with_message("the answer");
86        assert_eq!(resp.data, 42);
87        assert_eq!(resp.message, Some("the answer".to_string()));
88    }
89
90    #[test]
91    fn test_error_not_found() {
92        let err = Error::NotFound("route".to_string());
93        assert_eq!(err.to_string(), "Not Found: route");
94        let resp = err.into_response();
95        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
96    }
97
98    #[test]
99    fn test_error_validation() {
100        let err = Error::Validation("bad input".to_string());
101        assert_eq!(err.to_string(), "Validation Error: bad input");
102        let resp = err.into_response();
103        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
104    }
105
106    #[test]
107    fn test_error_internal() {
108        let err = Error::Internal("wow".to_string());
109        assert_eq!(err.to_string(), "Internal Error: wow");
110        let resp = err.into_response();
111        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
112    }
113
114    #[test]
115    fn test_error_unauthorized() {
116        let err = Error::Unauthorized("nope".to_string());
117        assert_eq!(err.to_string(), "Unauthorized: nope");
118        let resp = err.into_response();
119        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
120    }
121
122    #[test]
123    fn test_larastvel_result_type() {
124        let ok: LarastvelResult<i32> = Ok(1);
125        assert!(ok.is_ok());
126        let err: LarastvelResult<i32> = Err(Error::Internal("fail".to_string()));
127        assert!(err.is_err());
128    }
129}