summaryrefslogtreecommitdiff
path: root/src/types/response.rs
blob: d10bce9b490b184e0c21cf4386a2e3f5250f486d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use axum::{response::{IntoResponse, Response}, http::{StatusCode, Request, HeaderValue}, body::Body, headers::HeaderName};
use tower::ServiceExt;
use tower_http::services::ServeFile;
use tracing::instrument;

#[derive(Debug)]
pub enum ResponseCode {
    Success,
    Created,
    BadRequest,
    Unauthorized,
    Forbidden,
    NotFound,
    ImATeapot,
    InternalServerError
}

impl ResponseCode {

    pub fn code(self) -> StatusCode {
        match self {
            Self::Success => StatusCode::OK,
            Self::Created => StatusCode::CREATED,
            Self::BadRequest => StatusCode::BAD_REQUEST,
            Self::Unauthorized => StatusCode::UNAUTHORIZED,
            Self::Forbidden => StatusCode::FORBIDDEN,
            Self::NotFound => StatusCode::NOT_FOUND,
            Self::ImATeapot => StatusCode::IM_A_TEAPOT,
            Self::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR
        }
    }

    #[instrument()]
    pub fn text(self, msg: &str) -> Response {
        (self.code(), msg.to_owned()).into_response()
    }

    #[instrument()]
    pub fn json(self, json: &str) -> Response {
        let mut res = (self.code(), json.to_owned()).into_response();
        res.headers_mut().insert(
            HeaderName::from_static("content-type"), HeaderValue::from_static("application/json"),
        );
        res
    }

    #[instrument()]
    pub fn html(self, json: &str) -> Response {
        let mut res = (self.code(), json.to_owned()).into_response();
        res.headers_mut().insert(
            HeaderName::from_static("content-type"), HeaderValue::from_static("text/html"),
        );
        res
    }

    #[instrument()]
    pub async fn file(self, path: &str) -> Response {
        if path.chars().position(|c| c == '.' ).is_none() {
            return ResponseCode::BadRequest.text("Folders cannot be served");
        }
        let path = format!("public{}", path);
        let svc = ServeFile::new(path);
        let Ok(mut res) = svc.oneshot(Request::new(Body::empty())).await else {
            tracing::error!("Error while fetching file");
            return ResponseCode::InternalServerError.text("Error while fetching file");
        };
        if res.status() != StatusCode::OK {
            return ResponseCode::NotFound.text("File not found");
        }
        *res.status_mut() = self.code();
        res.into_response()
    }
}

pub type Result<T> = std::result::Result<T, Response>;