yassun7010 / serde_valid

JSON Schema based validation tool using serde.
MIT License
46 stars 10 forks source link

Cannot apply rule validation against raw identifiers #13

Closed Tenshock closed 1 year ago

Tenshock commented 1 year ago

Hi, thanks for this beautiful crate.

I found a bug I htink in the way the crate interprets attributes. The following code produces the following error:

#[derive(Validate)]
#[rule(sample_rule(r#type)]
struct MyStruct {
  pub r#type: bool
}

fn sample_rule(r#type: &bool) -> Result<(), serde_valid::validation::Error> {
  Ok(())
}
#[derive(Debug, PartialEq, Clone, Validate, Deserialize)]
   |                              ^^^^^^^^
   |
   = help: message: `"r#type"` is not a valid identifier

I know I can check the attribute r#type directly with #[validate(...)] but my use case implies multiples attributes.

yassun7010 commented 1 year ago

The current workaround is to use serde rename.

use serde_json::json;
use serde_valid::json::FromJsonValue;
use serde_valid::Validate;

#[derive(serde::Deserialize, Validate)]
#[rule(sample_rule(_type))]
struct MyStruct {
    #[serde(rename = "type")]
    pub _type: bool,
}

fn sample_rule(r#type: &bool) -> Result<(), serde_valid::validation::Error> {
    Ok(())
}

#[test]
fn test() -> Result<(), Box<dyn std::error::Error>> {
    let my_struct = MyStruct { _type: true };
    assert!(my_struct.validate().is_ok());

    assert_eq!(
        MyStruct::from_json_value(json!({"type": true}))?._type,
        my_struct._type
    );

    Ok(())
}
yassun7010 commented 1 year ago

The field name "type" seems to be an Issue proposed in many crates. A special workaround is provided.

https://github.com/yassun4dev/serde_valid/pull/15

yassun7010 commented 1 year ago

@Tenshock

I released v0.16.3.