async-graphql/src/types/enum.rs

41 lines
1022 B
Rust
Raw Normal View History

2020-03-19 09:20:12 +00:00
use crate::{Result, Type};
2020-03-01 10:54:34 +00:00
use graphql_parser::query::Value;
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,
}
#[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-03-04 02:38:07 +00:00
fn parse_enum(value: &Value) -> Option<Self> {
2020-03-04 03:51:42 +00:00
let value = match value {
Value::Enum(s) => Some(s.as_str()),
Value::String(s) => Some(s.as_str()),
_ => None,
};
2020-03-01 10:54:34 +00:00
2020-03-04 03:51:42 +00:00
value.and_then(|value| {
let items = Self::items();
for item in items {
if item.name == value {
return Some(item.value);
2020-03-01 16:52:05 +00:00
}
}
2020-03-04 03:51:42 +00:00
None
})
2020-03-01 16:52:05 +00:00
}
2020-03-02 00:24:49 +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-01 10:54:34 +00:00
return Ok(item.name.clone().into());
}
}
unreachable!()
}
}