Skip to content

Cleaner way to leverage serde renaming for nested elements #142

Description

@oldgalileo

After reading over the documentation of the Serialized provider, it seemed intuitively that it would allow you to do the following:

Expected behavior (non-functional)
#[derive(Debug, Serialize)]
struct Args {
    #[serde(rename = "database.max-connections")]
    pub database_max_connections: Option<u32>,
    #[serde(rename = "server.bind-address")]
    pub server_bind_address: Option<String>,
}

#[derive(Debug, Deserialize, Serialize)]
struct Config {
    database: DatabaseConfig,
    server: ServerConfig,
}

#[derive(Debug, Deserialize, Serialize)]
struct DatabaseConfig {
    pub host: String,
    pub port: u16,
    #[serde(rename = "max-connections")]
    pub max_connections: u32,
}

#[test]
fn test_override() {
    let args = Args {
        database_max_connections: Some(50),
        server_bind_address: Some("0.0.0.0".to_string()),
    };

    let config = Figment::from(Serialized::defaults(Config::default()))
        .merge(Serialized::from(&args, figment::Profile::Default))
        .extract::<Config>();

    assert_eq!(config.database.max_connections, 50);    
    assert_eq!(config.server.bind_address, "0.0.0.0");    
}

After reading over data, it looks like the best immediate solution to this is instead to do:

// the rest of the config 

#[derive(Debug, Serialize)]
struct Args {
    #[serde(rename = "database.max-connections")]
    pub database_max_connections: Option<u32>,
    #[serde(rename = "server.bind-address")]
    pub server_bind_address: Option<String>,
}

#[test]
fn test() {
    let args = Args {
        database_max_connections: Some(50),
        server_bind_address: Some("0.0.0.0".to_string()),
    };

    let mut figment = Figment::from(Serialized::defaults(Config::default()));
    
    let value = Value::serialize(&args).unwrap();
    if let Some(dict) = value.into_dict() {
        for (key, value) in dict.iter() {
            figment = figment.merge(Serialized::default(key, value));
        }
    }

    let config: Config = figment.extract().unwrap();
    
    assert_eq!(config.database.max_connections, 50);    
    assert_eq!(config.server.bind_address, "0.0.0.0");
}

Did I miss an easier way to accomplish this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions