redgold_schema/helpers/
easy_json.rs

1use crate::observability::errors::EnhanceErrorInfo;
2use crate::structs::{ErrorInfo, VersionInfo};
3use crate::{ErrorInfoContext, RgResult};
4use serde::Serialize;
5
6// #[async_trait]
7pub trait EasyJson {
8    fn json(&self) -> anyhow::Result<String, ErrorInfo>;
9    fn json_or(&self) -> String;
10    fn json_pretty(&self) -> anyhow::Result<String, ErrorInfo>;
11    fn json_pretty_or(&self) -> String;
12    fn write_json(&self, path: &str) -> RgResult<()>;
13}
14
15pub trait EasyJsonDeser {
16    fn json_from<'a, T: serde::Deserialize<'a>>(&'a self) -> anyhow::Result<T, ErrorInfo>;
17}
18
19impl EasyJsonDeser for String {
20    fn json_from<'a, T: serde::Deserialize<'a>>(&'a self) -> anyhow::Result<T, ErrorInfo> {
21        json_from(self)
22    }
23}
24
25impl EasyJsonDeser for &str {
26    fn json_from<'a, T: serde::Deserialize<'a>>(&'a self) -> anyhow::Result<T, ErrorInfo> {
27        json_from(self)
28    }
29}
30
31// #[async_trait]
32impl<T> EasyJson for T
33where T: Serialize {
34    fn json(&self) -> anyhow::Result<String, ErrorInfo> {
35        json(&self)
36    }
37
38    fn json_or(&self) -> String {
39        json_or(&self)
40    }
41
42    fn json_pretty(&self) -> anyhow::Result<String, ErrorInfo> {
43        json_pretty(&self)
44    }
45    fn json_pretty_or(&self) -> String {
46        json_pretty(&self).unwrap_or("json pretty failure".to_string())
47    }
48
49    fn write_json(&self, path: &str) -> RgResult<()> {
50        let string = self.json_or();
51        std::fs::write(path, string.clone()).error_info("error write json to path ").add(path.to_string()).add(" ").add(string)
52    }
53
54}
55
56#[test]
57pub fn json_trait_ser_test() {
58    let mut vers = VersionInfo::default();
59    vers.executable_checksum = "asdf".to_string();
60    println!("{}", vers.json_or());
61}
62
63pub fn json<T: Serialize>(t: &T) -> anyhow::Result<String, ErrorInfo> {
64    serde_json::to_string(&t).map_err(|e| ErrorInfo::error_info(format!("serde json ser error: {:?}", e)))
65}
66
67pub fn json_result<T: Serialize, E: Serialize>(t: &anyhow::Result<T, E>) -> String {
68    match t {
69        Ok(t) => json_or(t),
70        Err(e) => json_or(e),
71    }
72}
73
74pub fn json_or<T: Serialize>(t: &T) -> String {
75    json(t).unwrap_or("json ser failure of error".to_string())
76}
77
78pub fn json_pretty<T: Serialize>(t: &T) -> anyhow::Result<String, ErrorInfo> {
79    serde_json::to_string_pretty(&t).map_err(|e| ErrorInfo::error_info(format!("serde json ser error: {:?}", e)))
80}
81
82pub fn json_from<'a, T: serde::Deserialize<'a>>(t: &'a str) -> anyhow::Result<T, ErrorInfo> {
83    serde_json::from_str(t).map_err(|e| ErrorInfo::error_info(format!("serde json ser error: {:?}", e)))
84}