async-graphql/src/types/enum.rs

44 lines
1.2 KiB
Rust
Raw Normal View History

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
fn parse_enum(value: Value) -> InputValueResult<Self> {
let value = match &value {
Value::Enum(s) => s,
2020-05-16 13:14:26 +00:00
Value::String(s) => s.as_str(),
_ => return Err(InputValueError::ExpectedType(value)),
2020-03-04 03:51:42 +00:00
};
2020-03-01 10:54:34 +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
}
}
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!()
}
}