Skip to content

Commit

Permalink
refactor(model): Replace missing option attributes with defaults
Browse files Browse the repository at this point in the history
  • Loading branch information
jontze committed Aug 12, 2023
1 parent 6219ea7 commit 9d92208
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 13 deletions.
48 changes: 35 additions & 13 deletions src/models/price.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,16 @@ pub struct StationPrices {
/// Station open or closed
pub status: String,
/// Price for E5
#[serde(deserialize_with = "de_from_bool_or_number", default = "default_fuel")]
#[serde(deserialize_with = "de_from_bool_or_number", default)]
pub e5: Option<f64>,
/// Price for E10
#[serde(deserialize_with = "de_from_bool_or_number", default = "default_fuel")]
#[serde(deserialize_with = "de_from_bool_or_number", default)]
pub e10: Option<f64>,
/// Price for diesel
#[serde(deserialize_with = "de_from_bool_or_number", default = "default_fuel")]
#[serde(deserialize_with = "de_from_bool_or_number", default)]
pub diesel: Option<f64>,
}

/// This function should just return always null as fallback.
/// This is required as the custom deserialization can't handle missing values.
fn default_fuel() -> Option<f64> {
if 1 < 0 {
Some(1_f64)
} else {
None
}
}

fn de_from_bool_or_number<'de, D>(deserializer: D) -> Result<Option<f64>, D::Error>
where
D: Deserializer<'de>,
Expand Down Expand Up @@ -200,5 +190,37 @@ mod test {
.diesel,
None
);
assert_eq!(
prices_response
.prices
.get("55555555-4444-4444-4444-444444444444")
.unwrap()
.status,
"no prices"
);
assert_eq!(
prices_response
.prices
.get("55555555-4444-4444-4444-444444444444")
.unwrap()
.e5,
None
);
assert_eq!(
prices_response
.prices
.get("55555555-4444-4444-4444-444444444444")
.unwrap()
.e10,
None
);
assert_eq!(
prices_response
.prices
.get("55555555-4444-4444-4444-444444444444")
.unwrap()
.diesel,
None
);
}
}
6 changes: 6 additions & 0 deletions test/data/prices.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@
},
"44444444-4444-4444-4444-444444444444": {
"status": "no prices"
},
"55555555-4444-4444-4444-444444444444": {
"status": "no prices",
"e5": null,
"e10": null,
"diesel": null
}
}
}

0 comments on commit 9d92208

Please sign in to comment.