From a30bcf0f0f32d6b1c822c631cf22fa9b13a5616a Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Wed, 21 Sep 2022 23:51:38 +0200 Subject: Deserialize float model values as number from string --- src/json.rs | 10 ++++++++++ src/main.rs | 1 + src/models/model.rs | 5 ++++- 3 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 src/json.rs (limited to 'src') diff --git a/src/json.rs b/src/json.rs new file mode 100644 index 0000000..9515661 --- /dev/null +++ b/src/json.rs @@ -0,0 +1,10 @@ +use serde::{de, Deserialize, Deserializer}; +use serde_json::Value; + +pub fn number_from_string<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + Ok(match Value::deserialize(deserializer)? { + Value::String(s) => s.parse().map_err(de::Error::custom)?, + Value::Number(num) => num.as_f64().ok_or(de::Error::custom("Invalid number"))?, + _ => return Err(de::Error::custom("wrong type")), + }) +} diff --git a/src/main.rs b/src/main.rs index 66caecd..b13be75 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,6 +2,7 @@ mod config; mod db; mod errors; mod files; +mod json; mod logger; mod models; mod pagination; diff --git a/src/models/model.rs b/src/models/model.rs index 03f872e..469356f 100644 --- a/src/models/model.rs +++ b/src/models/model.rs @@ -1,4 +1,4 @@ -use crate::{config::CONFIG, db::get_client, errors::AppError}; +use crate::{config::CONFIG, db::get_client, errors::AppError, json::number_from_string}; use serde_json::json; use sqlx::types::JsonValue; use sqlx::Row; @@ -29,8 +29,11 @@ pub struct Model { pub struct ModelCreate { pub name: String, pub description: Option, + #[serde(deserialize_with = "number_from_string")] pub duration: f64, + #[serde(deserialize_with = "number_from_string")] pub height: f64, + #[serde(deserialize_with = "number_from_string")] pub weight: f64, pub printer: Option, pub material: Option, -- cgit v1.2.3-71-g8e6c