async-graphql/src/types/enum.rs

55 lines
1.3 KiB
Rust
Raw Normal View History

2020-03-03 11:15:18 +00:00
use crate::{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 value: T,
}
#[doc(hidden)]
#[async_trait::async_trait]
pub trait GQLEnum: GQLType + Sized + Eq + Send + Copy + Sized + 'static {
fn items() -> &'static [GQLEnumItem<Self>];
2020-03-04 02:38:07 +00:00
fn parse_enum(value: &Value) -> Option<Self> {
2020-03-01 10:54:34 +00:00
match value {
Value::Enum(s) => {
let items = Self::items();
for item in items {
if item.name == s {
2020-03-03 11:15:18 +00:00
return Some(item.value);
2020-03-01 10:54:34 +00:00
}
}
}
2020-03-03 11:15:18 +00:00
_ => {}
2020-03-01 10:54:34 +00:00
}
2020-03-03 11:15:18 +00:00
None
2020-03-01 10:54:34 +00:00
}
2020-03-04 02:38:07 +00:00
fn parse_json_enum(value: &serde_json::Value) -> Option<Self> {
2020-03-01 16:52:05 +00:00
match value {
serde_json::Value::String(s) => {
let items = Self::items();
for item in items {
if item.name == s {
2020-03-03 11:15:18 +00:00
return Some(item.value);
2020-03-01 16:52:05 +00:00
}
}
}
2020-03-03 11:15:18 +00:00
_ => {}
2020-03-01 16:52:05 +00:00
}
2020-03-03 11:15:18 +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!()
}
}