From 83261cef2acb91c63ebc518ca4fcac3506cc555a Mon Sep 17 00:00:00 2001 From: Renat Sadykov Date: Sat, 29 Aug 2020 23:18:57 +0300 Subject: [PATCH] Add the DateTime scalar --- src/scalars/datetime.rs | 19 ++++++++++++++++++- src/scalars/mod.rs | 11 ++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/scalars/datetime.rs b/src/scalars/datetime.rs index cecd3189..31de70f7 100644 --- a/src/scalars/datetime.rs +++ b/src/scalars/datetime.rs @@ -1,6 +1,23 @@ use crate::{InputValueError, InputValueResult, ScalarType, Value}; use async_graphql_derive::Scalar; -use chrono::{DateTime, Utc}; +use chrono::{DateTime, FixedOffset, Utc}; + +/// Implement the DateTime scalar +/// +/// The input/output is a string in RFC3339 format. +#[Scalar(internal, name = "DateTimeFixedOffset")] +impl ScalarType for DateTime { + fn parse(value: Value) -> InputValueResult { + match &value { + Value::String(s) => Ok(DateTime::parse_from_rfc3339(s)?), + _ => Err(InputValueError::ExpectedType(value)), + } + } + + fn to_value(&self) -> Value { + Value::String(self.to_rfc3339()) + } +} /// Implement the DateTime scalar /// diff --git a/src/scalars/mod.rs b/src/scalars/mod.rs index d3bf5ce4..2cf2e585 100644 --- a/src/scalars/mod.rs +++ b/src/scalars/mod.rs @@ -25,7 +25,7 @@ mod tests { use super::ID; use crate::Type; use bson::oid::ObjectId; - use chrono::{DateTime, NaiveDate, NaiveTime, Utc}; + use chrono::{DateTime, FixedOffset, NaiveDate, NaiveTime, Utc}; use uuid::Uuid; #[test] @@ -60,6 +60,15 @@ mod tests { "DateTimeUtc!" ); + assert_eq!( + as Type>::type_name(), + "DateTimeFixedOffset" + ); + assert_eq!( + as Type>::qualified_type_name(), + "DateTimeFixedOffset!" + ); + assert_eq!(::type_name(), "UUID"); assert_eq!(::qualified_type_name(), "UUID!");