From ae85517976e1b8bee7616a60ef967623574aef41 Mon Sep 17 00:00:00 2001 From: Caio Date: Fri, 15 May 2020 08:51:54 -0300 Subject: [PATCH] Impl Scalar for NaiveDate and NaiveTime --- src/scalars/mod.rs | 10 +++++++++- src/scalars/naive_date.rs | 22 ++++++++++++++++++++++ src/scalars/naive_time.rs | 22 ++++++++++++++++++++++ 3 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 src/scalars/naive_date.rs create mode 100644 src/scalars/naive_time.rs diff --git a/src/scalars/mod.rs b/src/scalars/mod.rs index 755c2397..30220f24 100644 --- a/src/scalars/mod.rs +++ b/src/scalars/mod.rs @@ -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!(::type_name(), "ID"); assert_eq!(::qualified_type_name(), "ID!"); + assert_eq!(::type_name(), "NaiveDate"); + assert_eq!(::qualified_type_name(), "NaiveDate!"); + + assert_eq!(::type_name(), "NaiveTime"); + assert_eq!(::qualified_type_name(), "NaiveTime!"); + assert_eq!( as Type>::type_name(), "DateTime"); assert_eq!( as Type>::qualified_type_name(), diff --git a/src/scalars/naive_date.rs b/src/scalars/naive_date.rs new file mode 100644 index 00000000..563a6b76 --- /dev/null +++ b/src/scalars/naive_date.rs @@ -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 { + match value { + Value::String(s) => Ok(NaiveDate::parse_from_str(&s, "%Y-%m-%d")?), + _ => Err(InputValueError::ExpectedType(value)), + } + } + + fn to_json(&self) -> Result { + Ok(self.format("%Y-%m-%d").to_string().into()) + } +} diff --git a/src/scalars/naive_time.rs b/src/scalars/naive_time.rs new file mode 100644 index 00000000..2a7c469e --- /dev/null +++ b/src/scalars/naive_time.rs @@ -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 { + match value { + Value::String(s) => Ok(NaiveTime::parse_from_str(&s, "%H:%M:%S")?), + _ => Err(InputValueError::ExpectedType(value)), + } + } + + fn to_json(&self) -> Result { + Ok(self.format("%H:%M:%S").to_string().into()) + } +}