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
use crate::Request;
use crate::{ssr::Js, Payload};
use axum::http::StatusCode;
use axum::response::{Html, IntoResponse};
use axum::Json;
use erased_serde::Serialize;

pub struct Props {
    data: Box<dyn Serialize>,
    http_code: StatusCode,
}

pub enum Response {
    Redirect(String),
    Props(Props),
}

impl Props {
    pub fn new(data: impl Serialize + 'static) -> Self {
        Props {
            data: Box::new(data),
            http_code: StatusCode::OK,
        }
    }

    pub fn new_with_status(data: impl Serialize + 'static, http_code: StatusCode) -> Self {
        Props {
            data: Box::new(data),
            http_code,
        }
    }
}

impl Response {
    pub fn render_to_string(&self, req: Request) -> impl IntoResponse {
        match self {
            Self::Props(Props { data, http_code }) => {
                let payload = Payload::new(&req, data).client_payload().unwrap();

                match Js::SSR.with(|ssr| ssr.borrow_mut().render_to_string(Some(&payload))) {
                    Ok(html) => (*http_code, Html(html)),
                    Err(_) => (*http_code, Html("500 Internal server error".to_string())),
                }
            }
            // TODO: Handle here other enum arms
            _ => todo!(),
        }
    }

    pub fn json(&self) -> impl IntoResponse {
        match self {
            Self::Props(Props { data, http_code }) => (*http_code, Json(data)).into_response(),
            _ => (StatusCode::INTERNAL_SERVER_ERROR, axum::Json("{}")).into_response(),
        }
    }
}