use ddd_cqrs_es::EventUpcaster;
/// A simple upcaster that converts old bank account opened payloads (v1)
/// to the newer version (v2) which includes an additional "currency" field.
struct AccountOpenedUpcaster;
impl EventUpcaster for AccountOpenedUpcaster {
type Error = &'static str;
/// The old schema version of the event stored in the database.
fn source_version(&self) -> u32 {
1
}
/// The new target schema version to upgrade to.
fn target_version(&self) -> u32 {
2
}
/// Performs the schema migration on the raw event payload.
fn upcast(&self, raw_payload: Vec<u8>) -> Result<Vec<u8>, Self::Error> {
// Parse raw payload as JSON (assuming serde_json is used)
let mut json: serde_json::Value = serde_json::from_slice(&raw_payload)
.map_err(|_| "Failed to deserialize v1 payload")?;
// Inject new fields with sensible default values
if let Some(obj) = json.as_object_mut() {
obj.insert("currency".to_owned(), serde_json::Value::String("USD".to_owned()));
}
// Serialize back to raw bytes
let upgraded_payload = serde_json::to_vec(&json)
.map_err(|_| "Failed to serialize v2 payload")?;
Ok(upgraded_payload)
}
}