use chrono::{DateTime, Utc};
use serde::Serialize;
#[cfg(feature = "optional-builders")]
use crate::common::builder::error::BuilderError;
#[derive(Clone, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Session {
pub id: String,
pub started_at: DateTime<Utc>,
pub handled: i64,
pub unhandled: i64,
}
#[cfg_attr(docsrs, doc(cfg(feature = "optional-builders")))]
#[cfg(feature = "optional-builders")]
impl Session {
pub fn builder() -> SessionBuilder {
SessionBuilder {
id: None,
started_at: None,
handled: None,
unhandled: None,
}
}
}
#[cfg_attr(docsrs, doc(cfg(feature = "optional-builders")))]
#[cfg(feature = "optional-builders")]
pub struct SessionBuilder {
pub id: Option<String>,
pub started_at: Option<DateTime<Utc>>,
pub handled: Option<i64>,
pub unhandled: Option<i64>,
}
#[cfg_attr(docsrs, doc(cfg(feature = "optional-builders")))]
#[cfg(feature = "optional-builders")]
impl SessionBuilder {
pub fn set_id<'a>(&mut self, id: impl Into<Option<&'a str>>) -> &mut Self {
self.id = id.into().map(|item| item.into());
self
}
pub fn set_started_at<'a>(
&mut self,
started_at: impl Into<Option<DateTime<Utc>>>,
) -> &mut Self {
self.started_at = started_at.into().map(|item| item.into());
self
}
pub fn set_handled(
&mut self,
handled: impl Into<Option<i64>>,
) -> &mut Self {
self.handled = handled.into();
self
}
pub fn set_unhandled(
&mut self,
unhandled: impl Into<Option<i64>>,
) -> &mut Self {
self.unhandled = unhandled.into();
self
}
pub fn build(&self) -> Result<Session, BuilderError> {
let mut missing_fields: Vec<String> = Vec::new();
if self.id.is_none() {
missing_fields.push("id".to_string());
}
if self.started_at.is_none() {
missing_fields.push("started_at".to_string());
}
if self.handled.is_none() {
missing_fields.push("handled".to_string());
}
if self.unhandled.is_none() {
missing_fields.push("unhandled".to_string());
}
if missing_fields.len() == 0 {
Ok(Session {
id: self.id.clone().unwrap(),
started_at: self.started_at.clone().unwrap(),
handled: self.handled.unwrap(),
unhandled: self.unhandled.unwrap(),
})
} else {
Err(BuilderError::MissingField {
context: "Event Session Builder".to_string(),
fields: missing_fields,
})
}
}
}
#[cfg(test)]
mod test {
#[cfg(feature = "optional-builders")]
#[test]
pub fn test_error_payload_event_session_builder() {
use super::Session;
use chrono::Timelike;
let reference_session = Session {
id: "1234".to_string(),
started_at: chrono::Utc::now().with_minute(10).unwrap(),
handled: 0,
unhandled: 0,
};
let session = Session::builder()
.set_id(reference_session.id.as_ref())
.set_started_at(reference_session.started_at)
.set_handled(reference_session.handled)
.set_unhandled(reference_session.unhandled)
.build()
.unwrap();
assert_eq!(session, reference_session);
}
}