From c3ba5ad5ebe1d5bb28ed0a340af93e8547b1c5bc Mon Sep 17 00:00:00 2001 From: Yigit Sever Date: Wed, 7 Apr 2021 01:08:31 +0300 Subject: Initial commit --- src/validators.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/validators.rs (limited to 'src/validators.rs') diff --git a/src/validators.rs b/src/validators.rs new file mode 100644 index 0000000..dbebee8 --- /dev/null +++ b/src/validators.rs @@ -0,0 +1,44 @@ +// Custom validators incoming data + +use log::error; +use serde::de::{Deserializer, Error as DeserializerError, Unexpected}; +use serde::ser::{Error as SerializerError, Serializer}; +use serde::Deserialize; + +pub mod validate_game_rating { + use super::*; + + const ERROR_MESSAGE: &str = "rating must be a number between 0 and 100"; + + pub fn deserialize<'de, D>(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let value = u8::deserialize(deserializer)?; + + if value > 100 { + error!("{}", ERROR_MESSAGE); + + return Err(DeserializerError::invalid_value( + Unexpected::Unsigned(u64::from(value)), + &ERROR_MESSAGE, + )); + } + + Ok(value) + } + + #[allow(clippy::trivially_copy_pass_by_ref)] + pub fn serialize(value: &u8, serializer: S) -> Result + where + S: Serializer, + { + if *value > 100 { + error!("{}", ERROR_MESSAGE); + + return Err(SerializerError::custom(ERROR_MESSAGE)); + } + + serializer.serialize_u8(*value) + } +} -- cgit v1.2.3-70-g09d2