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

serde default value from function #209

Open
DrLuke opened this issue Mar 11, 2023 · 1 comment
Open

serde default value from function #209

DrLuke opened this issue Mar 11, 2023 · 1 comment

Comments

@DrLuke
Copy link

DrLuke commented Mar 11, 2023

When defining a serde default value for a field using a function results in the generated value being set as the default value for the schema.

This is troublesome for fields that contain random data, like Uuids, as you probably don't want to define a default value. Also the value will be different each time the schema is generated.

There probably needs to be an attribute to ignore the default value but still make the field optional in the schema.

Minimal example:

use schemars::{schema_for, JsonSchema};
use serde::Deserialize;
use uuid::Uuid;

#[derive(Deserialize, JsonSchema)]
pub struct ExampleStruct {
    #[serde(default = "Uuid::new_v4")]
    uid: Uuid,
}

pub fn main() {
    let schema = schema_for!(ExampleStruct);
    println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}

Output:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "ExampleStruct",
  "type": "object",
  "properties": {
    "uid": {
      "default": "919c5b9d-db38-4c25-9ecb-4193fc08c78e",
      "type": "string",
      "format": "uuid"
    }
  }
}
@GREsau
Copy link
Owner

GREsau commented Aug 14, 2024

The easiest way to achieve this in schemars 1.0.0-alpha.3 is with the transform attribute, which can apply arbitrary modifications to generated schemas e.g.

#[derive(Deserialize, JsonSchema)]
pub struct ExampleStruct {
    #[serde(default = "Uuid::new_v4")]
    #[schemars(transform = remove_default)]
    uid: Uuid,
}

fn remove_default(schema: &mut Schema) {
    if let Some(obj) = schema.as_object_mut() {
        obj.remove("default");
    }
}

which then produces:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "ExampleStruct",
  "type": "object",
  "properties": {
    "uid": {
      "type": "string",
      "format": "uuid"
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants