use crate::services::Error as ServiceError;
use std::str::FromStr;
use strum_macros::EnumIter;
#[derive(EnumIter, Serialize, Deserialize, Debug, Copy, Clone, Hash, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum ConnectionType {
IncludeMessy,
IncludeElements,
Component,
Link,
Redirect,
}
impl ConnectionType {
pub fn name(self) -> &'static str {
match self {
ConnectionType::IncludeMessy => "include-messy",
ConnectionType::IncludeElements => "include-elements",
ConnectionType::Component => "component",
ConnectionType::Link => "link",
ConnectionType::Redirect => "redirect",
}
}
}
impl FromStr for ConnectionType {
type Err = ServiceError;
fn from_str(value: &str) -> Result<ConnectionType, ServiceError> {
match value {
"include-messy" => Ok(ConnectionType::IncludeMessy),
"include-elements" => Ok(ConnectionType::IncludeElements),
"component" => Ok(ConnectionType::Component),
"link" => Ok(ConnectionType::Link),
"redirect" => Ok(ConnectionType::Redirect),
_ => Err(ServiceError::InvalidEnumValue),
}
}
}
#[test]
fn name_serde() {
use strum::IntoEnumIterator;
for variant in ConnectionType::iter() {
let output = serde_json::to_string(&variant).expect("Unable to serialize JSON");
let serde_name: String =
serde_json::from_str(&output).expect("Unable to deserialize JSON");
assert_eq!(
&serde_name,
variant.name(),
"Serde name does not match variant name",
);
let converted: ConnectionType =
serde_name.as_str().parse().expect("Could not convert item");
assert_eq!(converted, variant, "Converted item does not match variant");
}
}