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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
use axum::{
body::Body,
http::StatusCode,
http::header,
response::IntoResponse,
response::Response,
};
#[cfg(feature="axum-view+cookie")]
use axum::http::header::SET_COOKIE;
use axum_extra::headers::HeaderValue;
use tera::Tera;
use toml::Table;
use std::marker::PhantomData;
use crate::HumusFormat;
use crate::HumusFormatFamily;
use crate::HumusProtoEngine;
use crate::HumusQuerySettings;
use crate::HumusView;
/* The engine itself */
/// 🌄 Tera based Templating Engine that writes out axum Response structs.
///
/// The engine uses logic and data from the configured [View] (V) type as well as
/// data and configuration provided by the [QuerySettings] (S) type to produce the
/// desired response with minimal code overhead inside your main logic.
///
/// <b>Note:</b> The private fields are [PhantomData] because the V, S and N
/// generics are only used for the implementation.
///
/// [PhantomData]: https://doc.rust-lang.org/std/marker/struct.PhantomData.html
///
/// The Engine operates in one of two modes determined by the [Format] (F) which
/// is [provided by the QuerySettings]:
/// * [Template Mode]: The [Format] describes which template to use for rendering
/// the [View] to some kind of text using Tera templates.
/// * [API Mode]: The [View] [serializes itself], usually to a [Json Response].
///
/// # Template Mode
///
/// In template mode the following sequence of events happens:
/// * status code, format and cookies are fetched.
/// (The cookie functionality is enabled with the `axum-view+cookie` feature)
/// * Template name and MimeType are fetched.
/// * The Template context is populated with metadatam the [View] and `template_config`.
/// * The [QuerySettings] are given the chance to populate the context
/// with their own values using the `initalize_template_context()` hook.
/// * The template gets rendered, resulting in further processing or an error response.
/// * The response is constructed using the MimeType from earlier and
/// the text from the template.
/// * The [View] is given a chance to alter the Response
/// using the `update_response()` hook.
/// * If the status code of the Response is "200 OK" (the default)
/// the status code and cookies fetched earlier are applied.
///
/// ## Template Symbols
///
/// The symbols defined for inside templates are:
/// * `view` will contain the template name, that coincides with
/// the basename of the template file.
/// * `format` will contain the format name (i.e. `html`, `text`, `json`)
/// * `mime_type` will contain the serialized mime_type
/// (i.e. `text/plain; charset=utf-8` or `application/json`)
/// * `http_status` will contain the numeric HTTP status code.
/// * `data` will contain the serde serialized [View]
/// * `extra` will be set to `template_config` which usually comes
/// from an `extra.toml` file in the template directory or a
/// configured custom location.
/// * others that were added by the [QuerySettings] in `initalize_template_context()`
///
/// # API Mode
///
/// In API mode the following, simpler sequence of events happens:
/// * status code, format and cookies are fetched.
/// (The cookie functionality is enabled with the `axum-view+cookie` feature)
/// * The [View] [serializes itself] using the `get_api_response()` callback.
/// * If the status code of the Response is "200 OK" (the default)
/// the status code and cookies fetched earlier are applied.
///
///
/// [View]: ./trait.HumusView.html
/// [QuerySettings]: ./trait.HumusQuerySettings.html
/// [Format]: ./trait.HumusFormat.html
/// [provided by the QuerySettings]: ./trait.HumusQuerySettings.html#tymethod.get_format
/// [Template Mode]: ./enum.HumusFormatFamily.html#variant.Template
/// [API Mode]: ./enum.HumusFormatFamily.html#variant.API
/// [serializes itself]: ./trait.HumusView.html#method.get_api_response
/// [Json Response]: https://docs.rs/axum/0.6.20/axum/struct.Json.html
///
#[derive(Clone)]
pub struct HumusEngine<V, S, F>
where V: HumusView<S, F>, S: HumusQuerySettings<F>, F: HumusFormat {
/// An instance of the tera templating engine.
pub tera: Tera,
/// If it was possible to read any extra configuration it will be stored here.
pub template_config: Option<Table>,
phantom_view: PhantomData<V>,
phantom_settings: PhantomData<S>,
phantom_format: PhantomData<F>,
}
impl<V, S, F> HumusEngine<V, S, F>
where V: HumusView<S, F>, S: HumusQuerySettings<F>, F: HumusFormat {
/// Creates a new Templating Engine.
///
/// An alternative would be converting from a [HumusProtoEngine].
///
/// [HumusProtoEngine]: ./struct.HumusProtoEngine.html
pub fn new(tera: Tera, template_config: Option<Table>) -> Self {
Self {
tera: tera,
template_config: template_config,
phantom_view: PhantomData,
phantom_settings: PhantomData,
phantom_format: PhantomData,
}
}
/// Takes settings and a view, converting it to a serveable response.
///
/// Example:
/// ```
/// async fn hello_world_handler(
/// State(arc_state): State<Arc<ServiceSharedState>>,
/// Extension(settings): Extension<QuerySettings>,
/// ) -> Response {
/// let state = Arc::clone(&arc_state);
///
/// state.templating_engine.render_view(
/// &settings,
/// View::Message{
/// title: "Hey There!".to_string(),
/// message: "You are an awesome creature!".to_string()
/// },
/// )
/// }
///
/// ```
pub fn render_view(
&self,
settings: &S,
view: V,
) -> Response {
let status_code = view.get_status_code(&settings);
let format = settings.get_format();
#[cfg(feature="axum-view+cookie")]
let cookie_string = view.get_cookie_header(&settings);
let mut response = match format.get_family() {
HumusFormatFamily::Template => {
let template_name = view.get_template_name();
let mime_type = format.get_mime_type();
let mut context = tera::Context::new();
context.insert("view", &template_name);
//intented for shared macros
context.insert("format", &format.get_name());
context.insert("mimetype", &mime_type.to_string());
context.insert("http_status", &status_code.as_u16());
context.insert("data", &view);
context.insert("extra", &self.template_config);
settings.initalize_template_context(&mut context);
match self.tera.render(
&(template_name.clone()+&format.get_file_extension()),
&context
) {
Ok(text) => {
let mut response = (
[(
header::CONTENT_TYPE,
HeaderValue::from_str(mime_type.as_ref())
.expect("MimeType should always be a valid header value.")
)],
Into::<Body>::into(text),
).into_response();
view.update_response(&mut response, &settings);
response
},
Err(e) => {
println!("There was an error while rendering template {}: {e:?}", template_name);
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Template error in {}, contact owner or see logs.\n", template_name)
).into_response()
}
}
}
HumusFormatFamily::API => {
view.get_api_response(&settings)
}
};
// Everything went well and nobody did the following work for us.
if response.status() == StatusCode::OK {
// Set status code
if status_code != StatusCode::OK {
*response.status_mut() = status_code;
}
// Set cookie header
#[cfg(feature="axum-view+cookie")]
if let Some(cookie_string) = cookie_string {
if let Ok(header_value) = HeaderValue::from_str(&cookie_string) {
response.headers_mut().append(
SET_COOKIE,
header_value,
);
}
}
}
// return response
response
}
}
impl<V, S, F> From<HumusProtoEngine> for HumusEngine<V, S, F>
where V: HumusView<S, F>, S: HumusQuerySettings<F>, F: HumusFormat {
fn from(e: HumusProtoEngine) -> Self {
Self::new(e.tera, e.template_config)
}
}
impl<V, S, F> From<HumusEngine<V, S, F>> for HumusProtoEngine
where V: HumusView<S, F>, S: HumusQuerySettings<F>, F: HumusFormat {
fn from(e: HumusEngine<V, S, F>) -> Self {
Self {
tera: e.tera,
template_config: e.template_config,
}
}
}