Skip to content

Commit 02ebd85

Browse files
authored
Merge pull request #64 from Shopify/ap.decimal-deserialize-serde-json
Use `serde_json` to deserialize `Decimal`
2 parents 9ab7407 + 7810675 commit 02ebd85

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

shopify_function/src/scalars/decimal.rs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use serde::{Deserialize, Serialize};
2-
use std::{ops::Deref, str::FromStr};
2+
use std::ops::Deref;
33

44
/// Convenience wrapper for converting between Shopify's `Decimal` scalar, which
55
/// is serialized as a `String`, and Rust's `f64`.
@@ -24,10 +24,12 @@ impl Deref for Decimal {
2424
}
2525

2626
impl TryFrom<String> for Decimal {
27-
type Error = std::num::ParseFloatError;
27+
type Error = &'static str;
2828

2929
fn try_from(value: String) -> Result<Self, Self::Error> {
30-
f64::from_str(value.as_str()).map(Self)
30+
serde_json::from_str(value.as_str())
31+
.map(Self)
32+
.map_err(|_| "Error parsing decimal: invalid float literal")
3133
}
3234
}
3335

@@ -61,6 +63,17 @@ mod tests {
6163
assert_eq!(123.4, decimal.as_f64());
6264
}
6365

66+
#[test]
67+
fn test_json_deserialization_error() {
68+
let decimal_value = serde_json::json!("123.4.5");
69+
let error =
70+
serde_json::from_value::<Decimal>(decimal_value).expect_err("Expected an error");
71+
assert_eq!(
72+
"Error parsing decimal: invalid float literal",
73+
error.to_string()
74+
);
75+
}
76+
6477
#[test]
6578
fn test_json_serialization() {
6679
let decimal = Decimal(123.4);

0 commit comments

Comments
 (0)