shared/api/
result.rs

1use serde::{de::DeserializeOwned, Deserialize, Serialize};
2
3#[derive(Serialize, Deserialize, Debug)]
4pub struct HttpStatus {
5    pub code: u16,
6    pub message: String,
7}
8
9#[derive(Serialize, Deserialize)]
10#[serde(tag = "type", content = "content", rename_all = "lowercase")]
11pub enum ResultResponse<T: Serialize + DeserializeOwned, E: Serialize + DeserializeOwned> {
12    #[serde(deserialize_with = "T::deserialize")]
13    Ok(T),
14    #[serde(deserialize_with = "E::deserialize")]
15    Err(E),
16}
17
18impl<T: Serialize + DeserializeOwned, E: Serialize + DeserializeOwned> ResultResponse<T, E> {
19    pub fn unwrap(self) -> T {
20        match self {
21            Self::Ok(x) => x,
22            Self::Err(x) => panic!(
23                "Could not unwrap ResultResponse. Error: [{}]",
24                serde_json::to_string(&x).unwrap()
25            ),
26        }
27    }
28}
29
30impl<T: Serialize + DeserializeOwned, E: Serialize + DeserializeOwned> From<ResultResponse<T, E>>
31    for Result<T, E>
32{
33    fn from(resp: ResultResponse<T, E>) -> Self {
34        match resp {
35            ResultResponse::Ok(x) => Ok(x),
36            ResultResponse::Err(x) => Err(x),
37        }
38    }
39}
40
41impl<T: Serialize + DeserializeOwned, E: Serialize + DeserializeOwned> From<Result<T, E>>
42    for ResultResponse<T, E>
43{
44    fn from(res: Result<T, E>) -> Self {
45        match res {
46            Ok(x) => Self::Ok(x),
47            Err(x) => Self::Err(x),
48        }
49    }
50}