//! HTTP utility functions for query strings and error responses. //! //! Helper functions for template path selection, query parameter formatting, //! and contextual error response generation with internationalization. use axum::{http, response::IntoResponse}; use axum_template::RenderHtml; use minijinja::Value; use std::fmt::Display; use unic_langid::LanguageIdentifier; use super::{context::WebContext, errors::WebError}; pub(super) type QueryParam<'a> = (&'a str, &'a str); pub(super) type QueryParams<'a> = Vec>; pub(super) fn build_querystring(query: QueryParams) -> String { query.iter().fold(String::new(), |acc, &tuple| { acc + tuple.0 + "=" + tuple.1 + "&" }) } /// Helper function to select the appropriate template path based on request type pub(super) fn select_template_path( template_name: &str, hxboosted: bool, hxrequest: bool, language: &LanguageIdentifier, ) -> String { let language_str = language.to_string().to_lowercase(); if hxboosted { format!("{}/{}.bare.html", language_str, template_name) } else if hxrequest { format!("{}/{}.partial.html", language_str, template_name) } else { format!("{}/{}.html", language_str, template_name) } } /// Helper function to select template with default "alert" name pub(super) fn select_alert_template( hxboosted: bool, hxrequest: bool, language: &LanguageIdentifier, ) -> String { select_template_path("alert", hxboosted, hxrequest, language) } /// Helper function to create contextual error responses pub(super) fn contextual_error_response( web_context: &WebContext, language: &LanguageIdentifier, template: &str, template_context: Value, error: E, status_code: Option, ) -> Result { let (err_bare, err_partial) = crate::errors::expand_error(error.to_string()); tracing::warn!(error = %error, "encountered error"); let error_message = web_context .i18n_context .locales .format_error(language, &err_bare, &err_partial); let status = status_code.unwrap_or(http::StatusCode::OK); let context = minijinja::context! { ..template_context, ..minijinja::context! { message => error_message, }}; Ok(( status, RenderHtml(template, web_context.engine.clone(), context), ) .into_response()) }