|
| 1 | +use serde::{Deserialize, Serialize}; |
| 2 | +use std::str::FromStr; |
| 3 | + |
| 4 | +/// Convenience wrapper for converting between Shopify's `Decimal` scalar, which |
| 5 | +/// is serialized as a `String`, and Rust's `f64`. |
| 6 | +#[derive(Deserialize, Serialize, Debug, PartialEq, Clone, Copy)] |
| 7 | +#[serde(try_from = "String")] |
| 8 | +#[serde(into = "String")] |
| 9 | +pub struct Decimal(pub f64); |
| 10 | + |
| 11 | +impl Decimal { |
| 12 | + /// Access the value as an `f64` |
| 13 | + pub fn as_f64(&self) -> f64 { |
| 14 | + self.0 |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +impl TryFrom<String> for Decimal { |
| 19 | + type Error = std::num::ParseFloatError; |
| 20 | + |
| 21 | + fn try_from(value: String) -> Result<Self, Self::Error> { |
| 22 | + f64::from_str(value.as_str()).map(Self) |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +impl From<Decimal> for String { |
| 27 | + fn from(value: Decimal) -> Self { |
| 28 | + value.0.to_string() |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +impl From<Decimal> for f64 { |
| 33 | + fn from(value: Decimal) -> Self { |
| 34 | + value.0 |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +impl From<f64> for Decimal { |
| 39 | + fn from(value: f64) -> Self { |
| 40 | + Self(value) |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +#[cfg(test)] |
| 45 | +mod tests { |
| 46 | + use super::Decimal; |
| 47 | + |
| 48 | + #[test] |
| 49 | + fn test_json_deserialization() { |
| 50 | + let decimal_value = serde_json::json!("123.4"); |
| 51 | + let decimal: Decimal = |
| 52 | + serde_json::from_value(decimal_value).expect("Error deserializing from JSON"); |
| 53 | + assert_eq!(123.4, decimal.as_f64()); |
| 54 | + } |
| 55 | + |
| 56 | + #[test] |
| 57 | + fn test_json_serialization() { |
| 58 | + let decimal = Decimal(123.4); |
| 59 | + let json_value = serde_json::to_value(decimal).expect("Error serializing to JSON"); |
| 60 | + assert_eq!(serde_json::json!("123.4"), json_value); |
| 61 | + } |
| 62 | +} |
0 commit comments