Projections
Projections are used to create read models or views from the series of events or state changes that occur in the system. The role of a projection is to transform a state into a more readable or convenient format, often optimized for queries.
- Data Transformation: Projections transform event-sourced data (state changes) into a format suitable for querying and display.
- Read Optimization: They create read models optimized for performance and specific use cases.
Implementation of Projections
application/src/projection.rs
use domain::todolist_event::TodoListEvent;
use framework::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
pub struct TodoListProjection {
pub in_progress: HashMap<usize, String>,
pub completed: HashMap<usize, String>,
}
impl Projection for TodoListProjection {
type Event = TodoListEvent;
fn apply(&mut self, events: &[Self::Event]) {
for event in events {
match event {
TodoListEvent::TaskAdded(index, name) => {
self.in_progress
.insert((*index).into(), name.clone().into());
}
TodoListEvent::TaskCompleted(index) => {
self.completed.insert(
(*index).into(),
self.in_progress.remove(&(*index).into()).unwrap(),
);
}
TodoListEvent::TaskRemoved(index) => {
self.in_progress.remove(&(*index).into());
}
}
}
}
}