2020-03-01 13:35:39 +00:00
|
|
|
use crate::{QueryError, GQLType, Result};
|
2020-03-01 10:54:34 +00:00
|
|
|
use graphql_parser::query::Value;
|
|
|
|
|
|
|
|
#[doc(hidden)]
|
|
|
|
pub struct GQLEnumItem<T> {
|
|
|
|
pub name: &'static str,
|
|
|
|
pub desc: Option<&'static str>,
|
|
|
|
pub value: T,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[doc(hidden)]
|
|
|
|
#[async_trait::async_trait]
|
|
|
|
pub trait GQLEnum: GQLType + Sized + Eq + Send + Copy + Sized + 'static {
|
|
|
|
fn items() -> &'static [GQLEnumItem<Self>];
|
|
|
|
|
|
|
|
fn parse_enum(value: Value) -> Result<Self> {
|
|
|
|
match value {
|
|
|
|
Value::Enum(s) => {
|
|
|
|
let items = Self::items();
|
|
|
|
for item in items {
|
|
|
|
if item.name == s {
|
|
|
|
return Ok(item.value);
|
|
|
|
}
|
|
|
|
}
|
2020-03-01 13:35:39 +00:00
|
|
|
Err(QueryError::InvalidEnumValue {
|
2020-03-01 10:54:34 +00:00
|
|
|
enum_type: Self::type_name(),
|
|
|
|
value: s,
|
|
|
|
}
|
|
|
|
.into())
|
|
|
|
}
|
|
|
|
_ => {
|
2020-03-01 13:35:39 +00:00
|
|
|
return Err(QueryError::ExpectedType {
|
2020-03-01 10:54:34 +00:00
|
|
|
expect: Self::type_name(),
|
|
|
|
actual: value,
|
|
|
|
}
|
|
|
|
.into())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn resolve_enum(self) -> Result<serde_json::Value> {
|
|
|
|
let items = Self::items();
|
|
|
|
for item in items {
|
|
|
|
if item.value == self {
|
|
|
|
return Ok(item.name.clone().into());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
unreachable!()
|
|
|
|
}
|
|
|
|
}
|