Skip to content

Specifying default value for an object should use object's existing default field values #662

Description

@jamesthurley

Let's say I have the following object definition in my schema:

"SeparatorConfig": {
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "lineThickness": {
      "type": "integer",
      "default": 1
    },
    "lineColor": {
      "type": [
        "string",
        "null"
      ],
      "default": "#B2000000"
    }
  }
},

So SeparatorConfig has two properties, both of which have default values.

Elsewhere in another object I have a field of type SeparatorConfig, and I'd like to make the entire field optional such that it defaults to an object with the correct default field values as defined above.

I could in theory do the following:

"separator": {
  "$ref": "#/definitions/SeparatorConfig",
  "default": {}
},

However the resulting generated code which produces this default value is:

super::SeparatorConfig {
  line_color: Default::default(),
  line_thickness: Default::default(),
}

Which produces:

{
  "line_color": null,
  "line_thickness": 0
}

Rather than the desired default:

{
  "line_color": "#B2000000",
  "line_thickness": 1
}

A better implementation for creating the default SeparatorConfig struct would be to use the existing builders you already generate:

builder::SeparatorConfig::default().try_into().expect("default should be valid")

We would also have to use the builder functions for defaults which specify only some properties:

"separator": {
  "$ref": "#/definitions/SeparatorConfig",
  "default": { "lineThickness": 5 }
},

Could produce:

builder::SeparatorConfig::default()
  .line_thickness(5_i64)
  .try_into()
  .expect("default should be valid")

rather than the current:

super::SeparatorConfig {
  line_color: Default::default(),
  line_thickness: 5_i64,
}

Overall this would make specifying default values for objects throughout a schema significantly easier.

The current alternatives are to either specify all the default field values at every level, duplicating a lot of default values (error prone), or not specifying defaults in the schema and manually constructing default structs in code when properties are None (cumbersome).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions