summaryrefslogtreecommitdiffstats
path: root/src/validators.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/validators.rs')
-rw-r--r--src/validators.rs44
1 files changed, 44 insertions, 0 deletions
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 @@
1// Custom validators incoming data
2
3use log::error;
4use serde::de::{Deserializer, Error as DeserializerError, Unexpected};
5use serde::ser::{Error as SerializerError, Serializer};
6use serde::Deserialize;
7
8pub mod validate_game_rating {
9 use super::*;
10
11 const ERROR_MESSAGE: &str = "rating must be a number between 0 and 100";
12
13 pub fn deserialize<'de, D>(deserializer: D) -> Result<u8, D::Error>
14 where
15 D: Deserializer<'de>,
16 {
17 let value = u8::deserialize(deserializer)?;
18
19 if value > 100 {
20 error!("{}", ERROR_MESSAGE);
21
22 return Err(DeserializerError::invalid_value(
23 Unexpected::Unsigned(u64::from(value)),
24 &ERROR_MESSAGE,
25 ));
26 }
27
28 Ok(value)
29 }
30
31 #[allow(clippy::trivially_copy_pass_by_ref)]
32 pub fn serialize<S>(value: &u8, serializer: S) -> Result<S::Ok, S::Error>
33 where
34 S: Serializer,
35 {
36 if *value > 100 {
37 error!("{}", ERROR_MESSAGE);
38
39 return Err(SerializerError::custom(ERROR_MESSAGE));
40 }
41
42 serializer.serialize_u8(*value)
43 }
44}