use crate::config::InertiaConfig;
use crate::protocol::Redirect;
use crate::request::RequestInfo;
use crate::response::InertiaResponse;
use crate::session::Flash;
use serde::Serialize;
use serde_json::Value;
use std::sync::Arc;
#[derive(Clone)]
pub struct Inertia {
#[allow(dead_code)]
pub(crate) config: Arc<InertiaConfig>,
pub(crate) request: Arc<RequestInfo>,
pub(crate) incoming_flash: Arc<Flash>,
}
impl Inertia {
pub fn from_parts(
config: Arc<InertiaConfig>,
request: RequestInfo,
incoming_flash: Flash,
) -> Self {
Self {
config,
request: Arc::new(request),
incoming_flash: Arc::new(incoming_flash),
}
}
pub fn request(&self) -> &RequestInfo {
&self.request
}
pub fn incoming_flash(&self) -> &Flash {
&self.incoming_flash
}
pub fn render<P: Serialize>(&self, component: impl Into<String>, props: P) -> InertiaResponse {
let value = match serde_json::to_value(&props) {
Ok(v) => v,
Err(e) => {
tracing::error!(error = %e, "veer: failed to serialize props for render; using null");
Value::Null
}
};
InertiaResponse::new(component, value)
}
pub fn redirect(&self, location: impl Into<String>) -> InertiaResponse {
let mut r = InertiaResponse::new(String::new(), Value::Null);
r.redirect = Some(Redirect::Internal(location.into()));
r
}
pub fn with_errors<E: crate::errors::IntoErrorBag>(&self, errors: E) -> InertiaResponse {
let mut r = InertiaResponse::new(String::new(), serde_json::Value::Null);
r.pending_flash.errors.extend(errors.into_error_bag());
r
}
pub fn location(&self, location: impl Into<String>) -> InertiaResponse {
let mut r = InertiaResponse::new(String::new(), Value::Null);
r.redirect = Some(Redirect::External(location.into()));
r
}
pub fn back(&self) -> InertiaResponse {
let to = self
.request
.referer
.clone()
.unwrap_or_else(|| "/".to_string());
self.redirect(to)
}
}