aboutsummaryrefslogtreecommitdiff
path: root/server/src/ui_responder.rs
blob: eb503a150f2f3518c8b6959ffb8f5555d465b2db (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
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/

use crate::request_info::RequestInfo;
use jellycommon::jellyobject::{ObjectBuffer, json::object_to_json};
use jellyui::render_view;
use rocket::response::{
    Responder,
    content::{RawHtml, RawJson},
};

pub enum UiResponse {
    Html(String),
    Json(String),
    Object(ObjectBuffer),
}

impl RequestInfo<'_> {
    pub fn respond_ui(&self, view: ObjectBuffer) -> UiResponse {
        if self.accept.is_json() || self.debug == "json" {
            let value = object_to_json(view.as_object());
            UiResponse::Json(serde_json::to_string(&value).unwrap())
        } else if self.debug == "raw" {
            UiResponse::Object(view)
        } else {
            UiResponse::Html(render_view(self.render_info(), view.as_object()))
        }
    }
}

impl<'r, 'o: 'r> Responder<'r, 'o> for UiResponse {
    fn respond_to(self, request: &'r rocket::Request<'_>) -> rocket::response::Result<'o> {
        match self {
            UiResponse::Html(x) => RawHtml(x).respond_to(request),
            UiResponse::Json(x) => RawJson(x).respond_to(request),
            UiResponse::Object(x) => x.to_bytes().respond_to(request),
        }
    }
}