2020-05-10 10:27:46 +00:00
|
|
|
use crate::{InputValueError, InputValueResult, Result, Type, Value};
|
2020-03-01 10:54:34 +00:00
|
|
|
|
2020-03-20 03:56:08 +00:00
|
|
|
#[allow(missing_docs)]
|
2020-03-19 09:20:12 +00:00
|
|
|
pub struct EnumItem<T> {
|
2020-03-01 10:54:34 +00:00
|
|
|
pub name: &'static str,
|
|
|
|
pub value: T,
|
|
|
|
}
|
|
|
|
|
2020-03-20 03:56:08 +00:00
|
|
|
#[allow(missing_docs)]
|
2020-03-01 10:54:34 +00:00
|
|
|
#[async_trait::async_trait]
|
2020-03-19 09:20:12 +00:00
|
|
|
pub trait EnumType: Type + Sized + Eq + Send + Copy + Sized + 'static {
|
|
|
|
fn items() -> &'static [EnumItem<Self>];
|
2020-03-01 10:54:34 +00:00
|
|
|
|
2020-05-11 13:47:24 +00:00
|
|
|
fn parse_enum(value: Value) -> InputValueResult<Self> {
|
2020-03-04 03:51:42 +00:00
|
|
|
let value = match value {
|
2020-05-11 13:47:24 +00:00
|
|
|
Value::Enum(s) => s,
|
|
|
|
Value::String(s) => s,
|
|
|
|
_ => return Err(InputValueError::ExpectedType(value)),
|
2020-03-04 03:51:42 +00:00
|
|
|
};
|
2020-03-01 10:54:34 +00:00
|
|
|
|
2020-05-10 10:27:46 +00:00
|
|
|
let items = Self::items();
|
|
|
|
for item in items {
|
|
|
|
if item.name == value {
|
|
|
|
return Ok(item.value);
|
2020-03-01 16:52:05 +00:00
|
|
|
}
|
2020-05-10 10:27:46 +00:00
|
|
|
}
|
|
|
|
Err(InputValueError::Custom(format!(
|
|
|
|
r#"Enumeration type "{}" does not contain the value "{}""#,
|
|
|
|
Self::type_name(),
|
|
|
|
value
|
|
|
|
)))
|
2020-03-01 16:52:05 +00:00
|
|
|
}
|
|
|
|
|
2020-03-25 03:39:28 +00:00
|
|
|
fn resolve_enum(&self) -> Result<serde_json::Value> {
|
2020-03-01 10:54:34 +00:00
|
|
|
let items = Self::items();
|
|
|
|
for item in items {
|
2020-03-02 00:24:49 +00:00
|
|
|
if item.value == *self {
|
2020-03-25 03:39:28 +00:00
|
|
|
return Ok(item.name.into());
|
2020-03-01 10:54:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
unreachable!()
|
|
|
|
}
|
|
|
|
}
|