Impl Scalar for NaiveDate and NaiveTime

This commit is contained in:
Caio 2020-05-15 08:51:54 -03:00
parent 6de85377f7
commit ae85517976
3 changed files with 53 additions and 1 deletions

View File

@ -6,6 +6,8 @@ mod floats;
mod id;
mod integers;
mod json;
mod naive_date;
mod naive_time;
mod string;
mod url;
@ -23,7 +25,7 @@ mod tests {
use super::ID;
use crate::Type;
use bson::oid::ObjectId;
use chrono::{DateTime, Utc};
use chrono::{DateTime, NaiveDate, NaiveTime, Utc};
use uuid::Uuid;
#[test]
@ -46,6 +48,12 @@ mod tests {
assert_eq!(<ID as Type>::type_name(), "ID");
assert_eq!(<ID as Type>::qualified_type_name(), "ID!");
assert_eq!(<NaiveDate as Type>::type_name(), "NaiveDate");
assert_eq!(<NaiveDate as Type>::qualified_type_name(), "NaiveDate!");
assert_eq!(<NaiveTime as Type>::type_name(), "NaiveTime");
assert_eq!(<NaiveTime as Type>::qualified_type_name(), "NaiveTime!");
assert_eq!(<DateTime::<Utc> as Type>::type_name(), "DateTime");
assert_eq!(
<DateTime::<Utc> as Type>::qualified_type_name(),

22
src/scalars/naive_date.rs Normal file
View File

@ -0,0 +1,22 @@
use crate::{InputValueError, InputValueResult, Result, ScalarType, Value};
use async_graphql_derive::Scalar;
use chrono::NaiveDate;
/// Implement the NaiveDate scalar
#[Scalar(internal)]
impl ScalarType for NaiveDate {
fn type_name() -> &'static str {
"NaiveDate"
}
fn parse(value: Value) -> InputValueResult<Self> {
match value {
Value::String(s) => Ok(NaiveDate::parse_from_str(&s, "%Y-%m-%d")?),
_ => Err(InputValueError::ExpectedType(value)),
}
}
fn to_json(&self) -> Result<serde_json::Value> {
Ok(self.format("%Y-%m-%d").to_string().into())
}
}

22
src/scalars/naive_time.rs Normal file
View File

@ -0,0 +1,22 @@
use crate::{InputValueError, InputValueResult, Result, ScalarType, Value};
use async_graphql_derive::Scalar;
use chrono::NaiveTime;
/// Implement the NaiveTime scalar
#[Scalar(internal)]
impl ScalarType for NaiveTime {
fn type_name() -> &'static str {
"NaiveTime"
}
fn parse(value: Value) -> InputValueResult<Self> {
match value {
Value::String(s) => Ok(NaiveTime::parse_from_str(&s, "%H:%M:%S")?),
_ => Err(InputValueError::ExpectedType(value)),
}
}
fn to_json(&self) -> Result<serde_json::Value> {
Ok(self.format("%H:%M:%S").to_string().into())
}
}