async_graphql/types/external/
duration.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
use std::str::FromStr;

use chrono::Duration;

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(std::time::Duration::from(
                iso8601::Duration::from_str(s)?,
            ))?),
            _ => Err(InputValueError::expected_type(value)),
        }
    }

    fn to_value(&self) -> Value {
        Value::String(self.to_string())
    }
}