use {
crate::{DatastarEvent, consts},
core::time::Duration,
};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ExecuteScript {
pub id: Option<String>,
pub retry: Duration,
pub script: String,
pub auto_remove: bool,
pub attributes: Vec<String>,
}
impl ExecuteScript {
pub fn new(script: impl Into<String>) -> Self {
Self {
id: None,
retry: Duration::from_millis(consts::DEFAULT_SSE_RETRY_DURATION),
script: script.into(),
auto_remove: consts::DEFAULT_EXECUTE_SCRIPT_AUTO_REMOVE,
attributes: vec![consts::DEFAULT_EXECUTE_SCRIPT_ATTRIBUTES.to_owned()],
}
}
pub fn id(mut self, id: impl Into<String>) -> Self {
self.id = Some(id.into());
self
}
pub fn retry(mut self, retry: Duration) -> Self {
self.retry = retry;
self
}
pub fn auto_remove(mut self, auto_remove: bool) -> Self {
self.auto_remove = auto_remove;
self
}
pub fn attributes(mut self, attributes: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.attributes = attributes.into_iter().map(Into::into).collect();
self
}
#[inline]
pub fn into_event(self) -> DatastarEvent {
self.into()
}
}
impl From<ExecuteScript> for DatastarEvent {
fn from(val: ExecuteScript) -> Self {
let mut data: Vec<String> = Vec::new();
if val.auto_remove != consts::DEFAULT_EXECUTE_SCRIPT_AUTO_REMOVE {
data.push(format!(
"{} {}",
consts::AUTO_REMOVE_DATALINE_LITERAL,
val.auto_remove
));
}
if val.attributes.len() != 1
|| val.attributes[0] != consts::DEFAULT_EXECUTE_SCRIPT_ATTRIBUTES
{
for attribute in &val.attributes {
data.push(format!(
"{} {}",
consts::ATTRIBUTES_DATALINE_LITERAL,
attribute
));
}
}
for line in val.script.lines() {
data.push(format!("{} {}", consts::SCRIPT_DATALINE_LITERAL, line));
}
Self {
event: consts::EventType::ExecuteScript,
id: val.id,
retry: val.retry,
data,
}
}
}