Skip to main content

EventFolder

Trait EventFolder 

Source
pub trait EventFolder: Default {
    type State;

    // Required methods
    fn apply(&mut self, event: &Event) -> bool;
    fn finalize(self) -> Option<Self::State>;
}
Expand description

Trait for reconstructing domain state from an event stream.

Implement this on your domain aggregate to fold raw events into typed state.

§Example

use allsource::{Event, EventFolder};

#[derive(Default)]
struct OrderFolder {
    total: f64,
    items: Vec<String>,
    status: String,
}

struct Order {
    total: f64,
    items: Vec<String>,
    status: String,
}

impl EventFolder for OrderFolder {
    type State = Order;

    fn apply(&mut self, event: &Event) -> bool {
        match event.event_type.as_str() {
            "order.created" => {
                self.status = "created".into();
                true
            }
            "order.item_added" => {
                if let Some(item) = event.payload.get("item").and_then(|v| v.as_str()) {
                    self.items.push(item.to_string());
                }
                if let Some(price) = event.payload.get("price").and_then(|v| v.as_f64()) {
                    self.total += price;
                }
                true
            }
            "order.completed" => {
                self.status = "completed".into();
                true
            }
            _ => false,
        }
    }

    fn finalize(self) -> Option<Self::State> {
        if self.status.is_empty() {
            None
        } else {
            Some(Order {
                total: self.total,
                items: self.items,
                status: self.status,
            })
        }
    }
}

Required Associated Types§

Source

type State

The domain state produced by folding events.

Required Methods§

Source

fn apply(&mut self, event: &Event) -> bool

Apply a single event to the accumulator. Returns true if the event was relevant and applied, false if it was ignored.

Source

fn finalize(self) -> Option<Self::State>

Finalize the folder into domain state. Returns None if no relevant events were applied (e.g., entity doesn’t exist).

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§