diff --git a/Cargo.toml b/Cargo.toml index f652d7dc..e8371f9e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,7 @@ unblock = ["blocking"] string_number = ["num-traits"] dataloader = ["futures-timer", "futures-channel", "lru"] tracing = ["tracinglib", "tracing-futures"] +decimal = ["rust_decimal"] [dependencies] async-graphql-derive = { path = "derive", version = "=2.9.5" } @@ -53,6 +54,7 @@ tracing-futures = { version = "0.2.5", optional = true, features = ["std-future" opentelemetry = { version = "0.13.0", optional = true } url = { version = "2.2.1", optional = true } uuid = { version = "0.8.2", optional = true, features = ["v4", "serde"] } +rust_decimal = { version = "1.14.3", optional = true } # Non-feature optional dependencies blocking = { version = "1.0.2", optional = true } diff --git a/src/lib.rs b/src/lib.rs index 79308023..963d658c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -71,6 +71,7 @@ //! - `uuid`: Integrate with the [`uuid` crate](https://crates.io/crates/uuid). //! - `string_number`: Enable the [StringNumber](types/struct.StringNumber.html). //! - `dataloader`: Support [DataLoader](dataloader/struct.DataLoader.html). +//! - `decimal`: Integrate with the [`rust_decimal` crate](https://crates.io/crates/rust_decimal). //! //! ## Integrations //! diff --git a/src/types/external/decimal.rs b/src/types/external/decimal.rs new file mode 100644 index 00000000..cbe65591 --- /dev/null +++ b/src/types/external/decimal.rs @@ -0,0 +1,19 @@ +use std::str::FromStr; + +use rust_decimal::Decimal; + +use crate::{InputValueError, InputValueResult, Scalar, ScalarType, Value}; + +#[Scalar(internal, name = "Decimal")] +impl ScalarType for Decimal { + fn parse(value: Value) -> InputValueResult { + match &value { + Value::String(s) => Ok(Decimal::from_str(s)?), + _ => Err(InputValueError::expected_type(value)), + } + } + + fn to_value(&self) -> Value { + Value::String(self.to_string()) + } +} diff --git a/src/types/external/mod.rs b/src/types/external/mod.rs index b949853c..02e98bd0 100644 --- a/src/types/external/mod.rs +++ b/src/types/external/mod.rs @@ -17,6 +17,8 @@ mod bson; mod chrono_tz; #[cfg(feature = "chrono")] mod datetime; +#[cfg(feature = "decimal")] +mod decimal; #[cfg(feature = "chrono")] mod naive_time; #[cfg(feature = "secrecy")]