|
| 1 | +use serde::{Deserialize, Serialize}; |
| 2 | +use serde_json::{json, Value}; |
| 3 | +use std::fmt::{self, Debug, Display}; |
| 4 | + |
| 5 | +#[derive(Serialize, Deserialize, Debug)] |
| 6 | +pub struct JsonWrapper<A> { |
| 7 | + pub code: u16, |
| 8 | + pub status: String, |
| 9 | + pub results: A, |
| 10 | +} |
| 11 | + |
| 12 | +impl JsonWrapper<Value> { |
| 13 | + pub fn error(code: u16, status: impl ToString) -> JsonWrapper<Value> { |
| 14 | + JsonWrapper { |
| 15 | + code, |
| 16 | + status: status.to_string(), |
| 17 | + results: json!({}), |
| 18 | + } |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +impl<'de, A> JsonWrapper<A> |
| 23 | +where |
| 24 | + A: Deserialize<'de> + Serialize + Debug, |
| 25 | +{ |
| 26 | + pub fn success(results: A) -> JsonWrapper<A> { |
| 27 | + JsonWrapper { |
| 28 | + code: 200, |
| 29 | + status: String::from("Success"), |
| 30 | + results, |
| 31 | + } |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +impl<'de, A> Display for JsonWrapper<A> |
| 36 | +where |
| 37 | + A: Deserialize<'de> + Serialize + Debug + Display, |
| 38 | +{ |
| 39 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 40 | + let out = json!(self).to_string(); |
| 41 | + write!(f, "{}", out) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +#[cfg(test)] |
| 46 | +mod test { |
| 47 | + use super::*; |
| 48 | + |
| 49 | + #[derive(Serialize, Deserialize, Debug, PartialEq)] |
| 50 | + struct TestResult { |
| 51 | + result: String, |
| 52 | + } |
| 53 | + |
| 54 | + impl Display for TestResult { |
| 55 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 56 | + let out = json!(self).to_string(); |
| 57 | + write!(f, "{}", out) |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + #[test] |
| 62 | + fn test_json_wrapper_success() { |
| 63 | + let expected = json!({ |
| 64 | + "code": 200, |
| 65 | + "status": "Success", |
| 66 | + "results": TestResult{ |
| 67 | + result: "Success".to_string(), |
| 68 | + }, |
| 69 | + }); |
| 70 | + let j = JsonWrapper::success(TestResult { |
| 71 | + result: "Success".to_string(), |
| 72 | + }); |
| 73 | + assert_eq!(j.to_string(), expected.to_string()); |
| 74 | + } |
| 75 | + |
| 76 | + #[test] |
| 77 | + fn test_json_wrapper_error() { |
| 78 | + let expected = json!({ |
| 79 | + "code": 400, |
| 80 | + "status": "Testing JsonWrapper error", |
| 81 | + "results": {}, |
| 82 | + }); |
| 83 | + let j = |
| 84 | + JsonWrapper::error(400, "Testing JsonWrapper error".to_string()); |
| 85 | + assert_eq!(j.to_string(), expected.to_string()); |
| 86 | + } |
| 87 | +} |
0 commit comments