Skip to main content

lib_humus/templating/
api_format.rs

1// SPDX-FileCopyrightText: 2026 Slatian <baschdel@disroot.org>
2//
3// SPDX-License-Identifier: AGPL-3.0-or-later
4
5use mime::Mime;
6use tinystr::tinystr;
7
8use crate::templating::HumusFormatIdentifier;
9
10/// Trait for types that describe the API format, that is managed by the application.
11///
12/// It is best implemented on an Enum type;
13pub trait HumusApiFormat: Clone + Send {
14	/// Returns the name of the format
15	fn get_name(&self) -> HumusFormatIdentifier;
16
17	/// Returns the Mimetype that is expected for this output format.
18	fn get_media_type(&self) -> Mime;
19
20	/// Constructs a view from its name.
21	fn from_name(name: &HumusFormatIdentifier) -> Option<Self>;
22
23	/// Returns a Vec of all variants for the purpose of enumerating them with their `get_name()` methods.
24	fn get_all() -> Vec<Self>;
25}
26
27/// Implementation of [HumusApiFormat] that can handle the cases where there is only a JSON API next to the templates.
28#[derive(Clone)]
29pub struct JsonOnlyApiFormat;
30
31impl HumusApiFormat for JsonOnlyApiFormat {
32	fn get_name(&self) -> HumusFormatIdentifier {
33		tinystr!(16, "json")
34	}
35
36	fn get_media_type(&self) -> Mime {
37		mime::APPLICATION_JSON
38	}
39
40	fn from_name(name: &HumusFormatIdentifier) -> Option<Self> {
41		match name.as_str() {
42			"json" => Some(Self),
43			_ => None,
44		}
45	}
46
47	fn get_all() -> Vec<Self> {
48		vec![Self]
49	}
50}