1use std::fmt::Debug;
2
3#[derive(Debug, thiserror::Error)]
5pub enum SerdeError {
6 #[error(transparent)]
7 Json(#[from] serde_json::Error),
8}
9
10#[derive(Debug, thiserror::Error)]
12pub enum DataParserError {
13 #[error("An error occurred during JSON encoding: {0}")]
14 EncodeJson(#[source] SerdeError),
15 #[error("An error occurred during JSON decoding: {0}")]
16 DecodeJson(#[source] SerdeError),
17}
18
19#[derive(Debug, Clone, strum::EnumIter, strum_macros::Display)]
20pub enum SerializationType {
21 #[strum(serialize = "json")]
22 Json,
23}
24
25#[async_trait::async_trait]
26pub trait DataEncoder:
27 serde::Serialize
28 + serde::de::DeserializeOwned
29 + Clone
30 + Send
31 + Sync
32 + Debug
33 + std::marker::Sized
34{
35 fn data_parser() -> DataParser {
36 DataParser::default()
37 }
38
39 fn encode_json(&self) -> Result<Vec<u8>, DataParserError> {
40 Self::data_parser().encode_json(self)
41 }
42
43 fn decode_json(encoded: &[u8]) -> Result<Self, DataParserError> {
44 Self::data_parser().decode_json(encoded)
45 }
46
47 fn to_json_value(&self) -> Result<serde_json::Value, DataParserError> {
48 Self::data_parser().to_json_value(self)
49 }
50}
51
52#[derive(Clone)]
53pub struct DataParser {
54 pub serialization_type: SerializationType,
55}
56
57impl Default for DataParser {
58 fn default() -> Self {
59 Self {
60 serialization_type: SerializationType::Json,
61 }
62 }
63}
64
65impl DataParser {
66 pub fn encode_json<T: DataEncoder>(
67 &self,
68 data: &T,
69 ) -> Result<Vec<u8>, DataParserError> {
70 serde_json::to_vec(&data)
71 .map_err(|e| DataParserError::EncodeJson(SerdeError::Json(e)))
72 }
73
74 pub fn to_json_value<T: serde::Serialize>(
75 &self,
76 data: &T,
77 ) -> Result<serde_json::Value, DataParserError> {
78 serde_json::to_value(data)
79 .map_err(|e| DataParserError::EncodeJson(SerdeError::Json(e)))
80 }
81
82 pub fn decode_json<T: DataEncoder>(
83 &self,
84 data: &[u8],
85 ) -> Result<T, DataParserError> {
86 serde_json::from_slice(data)
87 .map_err(|e| DataParserError::DecodeJson(SerdeError::Json(e)))
88 }
89}
90
91#[cfg(test)]
92mod tests {
93 use pretty_assertions::assert_eq;
94
95 use super::*;
96
97 #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
98 struct TestData {
99 field: String,
100 }
101
102 impl DataEncoder for TestData {}
103
104 #[tokio::test]
105 async fn test_encode_decode() {
106 let parser = DataParser::default();
107 let original_data = TestData {
108 field: "test".to_string(),
109 };
110 let encoded = parser.encode_json(&original_data).unwrap();
111 let decoded: TestData = parser.decode_json(&encoded).unwrap();
112 assert_eq!(original_data, decoded);
113 }
114}