livewire-rust 0.1.4

Livewire for Rust: server-rendered reactive components for Laravel for Rust.
Documentation
//! Model references: a field that holds a model crosses the wire as its class and key.
//!
//! A row is not sent to the browser: the snapshot carries the model's class name and key, and the
//! row is fetched again before the component renders. Upstream's Eloquent is synchronous; here the
//! fetch is an await, so the resolution lives in the request pipeline and not in a synthesizer —
//! [`ModelRef`] writes and reads the reference, and the derive's `hydrate_models` fetches the row.
//!
//! ```text
//! #[livewire(model)]
//! pub post: ModelRef<Post>,
//! ```

use laravel::model::Model;
use serde_json::{Map, Value};

use crate::error::LivewireError;
use crate::synthesizers::{Result as SynthResult, Synth, SynthError};

/// The synthesizer key a model reference carries.
const KEY: &str = "mdl";

/// A reference to one row, by its class and key.
///
/// The class comes from the model type, never from the request, so a forged snapshot cannot name a
/// type to instantiate.
#[derive(Debug)]
pub struct ModelRef<T: Model> {
    key: Option<T::Key>,
    row: Option<T>,
}

impl<T: Model> Default for ModelRef<T> {
    fn default() -> Self {
        Self { key: None, row: None }
    }
}

impl<T: Model> Clone for ModelRef<T> {
    fn clone(&self) -> Self {
        Self {
            key: self.key.clone(),
            row: self.row.clone(),
        }
    }
}

impl<T: Model> ModelRef<T> {
    /// A reference to an existing row, by key, whose row is fetched on the next update.
    #[must_use]
    pub fn referencing(key: T::Key) -> Self {
        Self {
            key: Some(key),
            row: None,
        }
    }

    /// A reference to a row the caller already holds.
    #[must_use]
    pub fn of(row: T) -> Self {
        Self {
            key: Some(T::META.key.get(&row).clone()),
            row: Some(row),
        }
    }

    /// The row, when it has been fetched.
    #[must_use]
    pub fn get(&self) -> Option<&T> {
        self.row.as_ref()
    }

    /// The key this reference still has to fetch, or `None` when it holds its row.
    #[must_use]
    pub fn unresolved(&self) -> Option<&T::Key> {
        if self.row.is_some() { None } else { self.key.as_ref() }
    }

    /// The key the reference carries, fetched or not.
    #[must_use]
    pub fn key(&self) -> Option<&T::Key> {
        self.key.as_ref()
    }

    /// The class the reference names, which is its model type's morph name.
    #[must_use]
    pub fn class() -> &'static str {
        T::META.morph
    }

    /// Takes the fetched row, or reports that the key names nothing.
    ///
    /// # Errors
    ///
    /// Returns [`LivewireError::ModelNotFound`] when `row` is `None`.
    pub fn found(&mut self, row: Option<T>) -> crate::component::Result<()> {
        let Some(row) = row else {
            return Err(LivewireError::ModelNotFound {
                class: T::META.morph.to_owned(),
                key: self.key.as_ref().map(ToString::to_string).unwrap_or_default(),
            });
        };

        self.key = Some(T::META.key.get(&row).clone());
        self.row = Some(row);

        Ok(())
    }
}

impl<T: Model> Synth for ModelRef<T> {
    const KEY: &'static str = KEY;

    fn dehydrate(&self) -> Option<(Value, Map<String, Value>)> {
        let mut meta = Map::new();
        meta.insert("s".to_owned(), Value::from(KEY));
        meta.insert("class".to_owned(), Value::from(T::META.morph));

        let key = self
            .key
            .as_ref()
            .and_then(|key| serde_json::to_value(key).ok())
            .unwrap_or(Value::Null);

        Some((key, meta))
    }

    fn hydrate(value: &Value, meta: Option<&Map<String, Value>>) -> SynthResult<Self> {
        if let Some(class) = meta.and_then(|meta| meta.get("class")).and_then(Value::as_str)
            && class != T::META.morph
        {
            return Err(SynthError::corrupt(format!(
                "a model reference to [{class}] cannot hydrate into [{}]",
                T::META.morph
            )));
        }

        if value.is_null() {
            return Ok(Self::default());
        }

        let key = serde_json::from_value::<T::Key>(value.clone())
            .map_err(|error| SynthError::corrupt(format!("the reference's key is not a key: {error}")))?;

        Ok(Self::referencing(key))
    }
}