Skip to main content

IntoEvents

Trait IntoEvents 

Source
pub trait IntoEvents<E: EsEvent>: Sized {
    type IdSource: IdSource;

    // Required method
    fn into_events(
        self,
        builder: EntityEventsBuilder<E, Self::IdSource>,
    ) -> EntityEvents<E>;
}
Expand description

Required trait for converting new entities into their initial events before persistence.

All NewEntity types must implement this trait and its into_events method to emit the initial events that need to be persisted, later the Entity is re-constructed by replaying these events.

§Example

use es_entity::*;
use serde::{Serialize, Deserialize};

entity_id!{ UserId }

#[derive(EsEvent, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[es_event(id = "UserId")]
pub enum UserEvent {
    Initialized { id: UserId, name: String },
    NameUpdated { name: String }
}

// The main `Entity` type
#[derive(EsEntity)]
pub struct User {
    pub id: UserId,
    name: String,
    events: EntityEvents<UserEvent>
}

// The `NewEntity` type used for initialization. It has no id: the repo
// generates one and hands it over through the builder.
pub struct NewUser {
    name: String
}

// The `IntoEvents` implementation which emits an event stream.
// These events help track `Entity` state mutations
// Returns the `EntityEvents<UserEvent>`
impl IntoEvents<UserEvent> for NewUser {
    type IdSource = FromRepo;

    fn into_events(self, builder: EntityEventsBuilder<UserEvent, FromRepo>) -> EntityEvents<UserEvent> {
        let id = builder.id();
        builder.initial_events([UserEvent::Initialized {
            id,
            name: self.name,
        }])
    }
}

// The `TryFromEvents` implementation to hydrate entities by replaying events chronologically.
impl TryFromEvents<UserEvent> for User {
    fn try_from_events(events: EntityEvents<UserEvent>) -> Result<Self, EntityHydrationError> {
        let mut name = String::new();
        for event in events.iter_all() {
             match event {
                UserEvent::Initialized { name: n, .. } => name = n.clone(),
                UserEvent::NameUpdated { name: n, .. } => name = n.clone(),
                // ...similarly other events can be matched
            }
        }
        Ok(User { id: events.id().clone(), name, events })
    }
}

Required Associated Types§

Source

type IdSource: IdSource

Where the id comes from: FromRepo (the repo generates it and the New* type has no id field) or FromCaller (the caller puts a deterministic one in the New* value). It must agree with the repo’s id(source = ..); a mismatch does not compile.

Required Methods§

Source

fn into_events( self, builder: EntityEventsBuilder<E, Self::IdSource>, ) -> EntityEvents<E>

Method to implement which emits event stream from a NewEntity

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§