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

Add example of parsing JSON with serde #100

Merged
merged 1 commit into from
Nov 19, 2023
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
35 changes: 22 additions & 13 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions examples/serde_complex/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "serde_complex"
version = "0.1.0"
edition = "2021"
publish = false
authors = ["Serhii Potapov <[email protected]>"]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
nutype = { path = "../../nutype", features = ["serde"] }
serde = { version = "1.0.192", features = ["derive"] }
serde_json = "1.0.108"
96 changes: 96 additions & 0 deletions examples/serde_complex/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
use nutype::nutype;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Product {
name: Name,
image_url: ImageUrl,
price: Price,
}

#[nutype(
sanitize(trim),
validate(not_empty, char_len_max = 50),
derive(Debug, Clone, PartialEq, AsRef, Serialize, Deserialize)
)]
struct Name(String);

#[nutype(
sanitize(trim),
validate(
predicate = |url| url.starts_with("https://") && url.ends_with(".jpg")
),
derive(Debug, Clone, PartialEq, AsRef, Serialize, Deserialize)
)]
struct ImageUrl(String);

// Note: in the real world, you should use decimal instead of float to represent price.
#[nutype(
validate(greater = 0.0, less = 1000_000.0),
derive(Debug, Clone, PartialEq, AsRef, Serialize, Deserialize)
)]
struct Price(f64);

fn main() {
{
// Invalid because name is empty
let json = r#"
{
"name": " ",
"image_url": "https://example.com/image.jpg",
"price": 9.99
}
"#;
let res: Result<Product, _> = serde_json::from_str(json);
let err = res.unwrap_err();
assert!(err.to_string().contains("empty, expected valid Name"));
}

{
// Invalid because image_url does not end with ".jpg"
let json = r#"
{
"name": "FlySniper",
"image_url": "https://example.com/image.png",
"price": 9.99
}
"#;
let res: Result<Product, _> = serde_json::from_str(json);
let err = res.unwrap_err();
assert!(err.to_string().contains("invalid, expected valid ImageUrl"));
}

{
// Invalid because the price is negative
let json = r#"
{
"name": "FlySniper",
"image_url": "https://example.com/image.jpg",
"price": -0.1
}
"#;
let res: Result<Product, _> = serde_json::from_str(json);
let err = res.unwrap_err();
assert!(err.to_string().contains("too small, expected valid Price"));
}

{
// Valid product
let json = r#"
{
"name": "FlySniper\n",
"image_url": "https://example.com/image.jpg",
"price": 9.99
}
"#;
let product: Product = serde_json::from_str(json).unwrap();
assert_eq!(
product,
Product {
name: Name::new("FlySniper").unwrap(),
image_url: ImageUrl::new("https://example.com/image.jpg").unwrap(),
price: Price::new(9.99).unwrap(),
}
)
}
}
7 changes: 6 additions & 1 deletion nutype_macros/src/common/gen/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,13 @@ pub fn gen_impl_trait_serde_deserialize(
) -> TokenStream {
let inner_type: InnerType = inner_type.into();
let raw_value_to_result: TokenStream = if maybe_error_type_name.is_some() {
let type_name_str = type_name.to_string();
quote! {
#type_name::new(raw_value).map_err(<DE::Error as serde::de::Error>::custom)
#type_name::new(raw_value).map_err(|validation_error| {
// Add a hint about which type is causing the error,
let err_msg = format!("{validation_error}, expected valid {}", #type_name_str);
<DE::Error as serde::de::Error>::custom(err_msg)
})
}
} else {
quote! {
Expand Down
2 changes: 1 addition & 1 deletion test_suite/tests/any.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ mod traits {

{
let err = serde_json::from_str::<LinePoint>("{\"x\":7,\"y\":9}").unwrap_err();
assert_eq!(err.to_string(), "invalid");
assert_eq!(err.to_string(), "invalid, expected valid LinePoint");
}

{
Expand Down
Loading