add ID scalar

This commit is contained in:
sunli 2020-03-02 00:59:04 +08:00
parent 5d1a1e3da4
commit af8d4d0f4b
7 changed files with 60 additions and 4 deletions

View File

@ -34,6 +34,7 @@
- [X] Float
- [X] String
- [X] Bool
- [X] ID
- [X] DateTime
- [X] UUID
- Complex Types

View File

@ -1,5 +1,4 @@
use crate::{QueryError, Result, Scalar, Value};
use anyhow::Error;
use chrono::{DateTime, TimeZone, Utc};
impl Scalar for DateTime<Utc> {

57
src/id.rs Normal file
View File

@ -0,0 +1,57 @@
use crate::{QueryError, Result, Scalar, Value};
use std::ops::{Deref, DerefMut};
#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
pub struct ID(String);
impl Deref for ID {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for ID {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl Scalar for ID {
fn type_name() -> &'static str {
"ID"
}
fn parse(value: Value) -> Result<Self> {
match value {
Value::Int(n) => Ok(ID(n.as_i64().unwrap().to_string())),
Value::String(s) => Ok(ID(s)),
_ => {
return Err(QueryError::ExpectedType {
expect: Self::type_name().to_string(),
actual: value,
}
.into())
}
}
}
fn parse_from_json(value: serde_json::Value) -> Result<Self> {
match value {
serde_json::Value::Number(n) if n.is_i64() => Ok(ID(n.as_i64().unwrap().to_string())),
serde_json::Value::String(s) => Ok(ID(s)),
_ => {
return Err(QueryError::ExpectedJsonType {
expect: Self::type_name().to_string(),
actual: value,
}
.into())
}
}
}
fn into_json(self) -> Result<serde_json::Value> {
Ok(self.0.clone().into())
}
}

View File

@ -36,6 +36,7 @@ extern crate thiserror;
mod context;
mod r#enum;
mod error;
mod id;
mod query;
mod scalar;
mod r#type;
@ -54,6 +55,7 @@ pub use async_graphql_derive::{Enum, InputObject, Object};
pub use context::{Context, ContextField, ContextSelectionSet, Data, Variables};
pub use error::{ErrorWithPosition, PositionError, QueryError, QueryParseError};
pub use graphql_parser::query::Value;
pub use id::ID;
pub use query::QueryBuilder;
pub use scalar::Scalar;

View File

@ -1,6 +1,5 @@
use crate::r#type::{GQLInputValue, GQLOutputValue, GQLType};
use crate::{ContextSelectionSet, QueryError, Result};
use anyhow::Error;
use graphql_parser::query::Value;
pub trait Scalar: Sized + Send {

View File

@ -1,5 +1,4 @@
use crate::{ContextSelectionSet, ErrorWithPosition, QueryError, Result};
use anyhow::Error;
use graphql_parser::query::Value;
#[doc(hidden)]

View File

@ -1,5 +1,4 @@
use crate::{QueryError, Result, Scalar, Value};
use anyhow::Error;
use uuid::Uuid;
impl Scalar for Uuid {