use crate::proto::{CommandBook, Cover, Edition, EventBook, Query};
use super::constants::{DEFAULT_EDITION, UNKNOWN_DOMAIN};
pub trait CoverExt {
fn cover(&self) -> Option<&Cover>;
fn domain(&self) -> &str {
self.cover()
.map(|c| c.domain.as_str())
.unwrap_or(UNKNOWN_DOMAIN)
}
fn correlation_id(&self) -> &str {
self.cover()
.map(|c| c.correlation_id.as_str())
.unwrap_or("")
}
fn root_id_hex(&self) -> Option<String> {
self.cover()
.and_then(|c| c.root.as_ref())
.map(|u| hex::encode(&u.value))
}
fn root_uuid(&self) -> Option<uuid::Uuid> {
self.cover()
.and_then(|c| c.root.as_ref())
.and_then(|u| uuid::Uuid::from_slice(&u.value).ok())
}
fn has_correlation_id(&self) -> bool {
!self.correlation_id().is_empty()
}
fn edition(&self) -> &str {
self.cover()
.and_then(|c| c.edition.as_ref())
.map(|e| e.name.as_str())
.filter(|e| !e.is_empty())
.unwrap_or(DEFAULT_EDITION)
}
fn edition_struct(&self) -> Option<&crate::proto::Edition> {
self.cover().and_then(|c| c.edition.as_ref())
}
fn edition_opt(&self) -> Option<&str> {
self.cover()
.and_then(|c| c.edition.as_ref())
.map(|e| e.name.as_str())
.filter(|n| !n.is_empty())
}
fn routing_key(&self) -> String {
self.domain().to_string()
}
fn cache_key(&self) -> String {
let edition = self.edition();
let domain = self.domain();
let root = self.root_id_hex().unwrap_or_default();
format!("{edition}:{domain}:{root}")
}
}
impl CoverExt for EventBook {
fn cover(&self) -> Option<&Cover> {
self.cover.as_ref()
}
}
impl CoverExt for CommandBook {
fn cover(&self) -> Option<&Cover> {
self.cover.as_ref()
}
}
impl CoverExt for Query {
fn cover(&self) -> Option<&Cover> {
self.cover.as_ref()
}
}
impl CoverExt for Cover {
fn cover(&self) -> Option<&Cover> {
Some(self)
}
}
impl Cover {
pub fn stamp_edition_if_empty(&mut self, edition: &str) {
if self.edition.as_ref().is_none_or(|e| e.name.is_empty()) {
self.edition = Some(Edition {
name: edition.to_string(),
divergences: vec![],
});
}
}
}