Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add chrono::Duration custom scalar #689

Merged
merged 2 commits into from
Nov 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ dataloader = ["futures-timer", "futures-channel", "lru"]
tracing = ["tracinglib", "tracing-futures"]
decimal = ["rust_decimal"]
cbor = ["serde_cbor"]
chrono-duration = ["chrono", "iso8601-duration"]

[dependencies]
async-graphql-derive = { path = "derive", version = "=2.11.0" }
Expand Down Expand Up @@ -50,6 +51,7 @@ mime = "0.3.15"
bson = { version = "2.0.0", optional = true, features = ["chrono-0_4"] }
chrono = { version = "0.4.19", optional = true }
chrono-tz = { version = "0.5.3", optional = true }
iso8601-duration = { version = "0.1.0", optional = true }
log = { version = "0.4.14", optional = true }
secrecy = { version = "0.7.0", optional = true }
tracinglib = { version = "0.1.25", optional = true, package = "tracing" }
Expand Down
21 changes: 21 additions & 0 deletions src/types/external/duration.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use chrono::Duration;
use iso8601_duration as iso8601;

use crate::{InputValueError, InputValueResult, Scalar, ScalarType, Value};

/// Implement the Duration scalar
///
/// The input/output is a string in ISO8601 format.
#[Scalar(internal, name = "Duration", specified_by_url = "https://en.wikipedia.org/wiki/ISO_8601#Durations")]
impl ScalarType for Duration {
fn parse(value: Value) -> InputValueResult<Self> {
match &value {
Value::String(s) => Ok(Duration::from_std(iso8601::Duration::parse(s)?.to_std())?),
_ => Err(InputValueError::expected_type(value)),
}
}

fn to_value(&self) -> Value {
Value::String(self.to_string())
}
}
2 changes: 2 additions & 0 deletions src/types/external/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ mod bson;
mod chrono_tz;
#[cfg(feature = "chrono")]
mod datetime;
#[cfg(feature = "chrono-duration")]
mod duration;
#[cfg(feature = "decimal")]
mod decimal;
#[cfg(feature = "chrono")]
Expand Down