genies_core/
lib.rs

1/*
2 * @Author: tzw
3 * @Date: 2021-10-31 03:05:39
4 * @LastEditors: tzw
5 * @LastEditTime: 2021-11-29 22:23:13
6 */
7pub mod error;
8pub mod jwt;
9pub mod condition;
10
11
12/// 自定义 Result 类型,接受两个泛型参数:T 为成功时的返回类型,E 为错误类型
13pub type Result<T> = std::result::Result<T, crate::error::Error>;
14
15
16
17use crate::error::Error;
18// use actix_http::Response;
19use salvo::prelude::*;
20use serde::de::DeserializeOwned;
21use serde::{Deserialize, Serialize};
22use serde_json::json;
23
24// pub mod jwt;
25
26pub const CODE_SUCCESS: &str = "SUCCESS";
27pub const CODE_FAIL: &str = "FAIL";
28
29pub const CODE_SUCCESS_I32: i32 = 1;
30pub const CODE_FAIL_I32: i32 = 0;
31
32/// http接口返回模型结构,提供基础的 code,msg,data 等json数据结构
33#[derive(Debug, Serialize, Deserialize, Clone,Default)]
34pub struct RespVO<T> {
35    pub code: Option<String>,
36    pub msg: Option<String>,
37    pub data: Option<T>,
38}
39
40#[async_trait]
41impl<T> Writer for RespVO<T>
42    where
43        T: Serialize + DeserializeOwned + Clone+Send,
44{
45    async fn write(mut self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
46        res.headers_mut().insert("Content-Type", "text/json;charset=UTF-8".parse().unwrap());
47        match self.code {
48            Some(code) if code.eq("dapr") =>{
49                res.render(serde_json::to_string(&self.data.unwrap()).unwrap());
50            },
51            _=>{
52                res.render(self.to_string());
53            }
54        }
55    }
56}
57impl<T> RespVO<T>
58where
59    T: Serialize + DeserializeOwned + Clone+Send,
60{
61    pub fn from_result(arg: &Result<T>) -> Self {
62        if arg.is_ok() {
63            Self {
64                code: Some(CODE_SUCCESS.to_string()),
65                msg: None,
66                data: arg.clone().ok(),
67            }
68        } else {
69            Self {
70                code: Some(CODE_FAIL.to_string()),
71                msg: Some(arg.clone().err().unwrap().to_string()),
72                data: None,
73            }
74        }
75    }
76
77    pub fn from(arg: &T) -> Self {
78        Self {
79            code: Some(CODE_SUCCESS.to_string()),
80            msg: None,
81            data: Some(arg.clone()),
82        }
83    }
84
85    pub fn from_error(code: &str, arg: &Error) -> Self {
86        let mut code_str = code.to_string();
87        if code_str.is_empty() {
88            code_str = CODE_FAIL.to_string();
89        }
90        Self {
91            code: Some(code_str),
92            msg: Some(arg.to_string()),
93            data: None,
94        }
95    }
96
97    pub fn from_error_info(code: &str, info: &str) -> Self {
98        let mut code_str = code.to_string();
99        if code_str.is_empty() {
100            code_str = CODE_FAIL.to_string();
101        }
102        Self {
103            code: Some(code_str),
104            msg: Some(info.to_string()),
105            data: None,
106        }
107    }
108
109
110    pub fn resp_json(&self) -> Self {
111        Self {
112            code: self.code.clone(),
113            msg: self.msg.clone(),
114            data: self.data.clone(),
115        }
116    }
117
118
119
120    /// Dapr pubsub  所需要的返回值
121    pub fn to_dapr_pubsub() -> Self {
122        Self{
123            code: None,
124            msg: None,
125            data: None
126        }
127    }
128    // /// 标记 Dapr pubsub 消息重试
129    pub fn is_retry(&mut self) ->RespVO::<serde_json::Value>  {
130        RespVO::<serde_json::Value> {
131            code: Some("dapr".to_string()),
132            msg: None,
133            data: Some(json!({"status": "RETRY"})),
134        }
135    }
136    /// 标记 Dapr pubsub 消息消费成功
137    pub fn is_success(&mut self)-> RespVO::<serde_json::Value> {
138        RespVO::<serde_json::Value> {
139            code: Some("dapr".to_string()),
140            msg: None,
141            data: Some(json!({"status": "SUCCESS"})),
142        }
143
144    }
145
146}
147
148impl<T> ToString for RespVO<T>
149where
150    T: Serialize + DeserializeOwned + Clone,
151{
152    fn to_string(&self) -> String {
153        serde_json::to_string(self).unwrap()
154    }
155}
156
157/// 兼容Java返回值
158#[derive(Debug, Serialize, Deserialize, Clone,Default)]
159pub struct ResultDTO<T> {
160    pub status: Option<i32>,
161    pub message: Option<String>,
162    pub data: Option<T>,
163}
164#[async_trait]
165impl<T> Writer for ResultDTO<T>
166    where
167        T: Serialize + DeserializeOwned + Clone+Send,
168{
169    async fn write(mut self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
170        res.headers_mut().insert("Content-Type", "text/json;charset=UTF-8".parse().unwrap());
171        match self.status {
172            _=>{
173                res.render(self.to_string());
174            }
175        }
176    }
177}
178
179impl<T> ResultDTO<T>
180where
181    T: Serialize + DeserializeOwned + Clone,
182{
183    pub fn from_result(arg: &Result<T>) -> Self {
184        if arg.is_ok() {
185            Self {
186                status: Some(CODE_SUCCESS_I32),
187                message: None,
188                data: arg.clone().ok(),
189            }
190        } else {
191            Self {
192                status: Some(CODE_FAIL_I32),
193                message: Some(arg.clone().err().unwrap().to_string()),
194                data: None,
195            }
196        }
197    }
198
199    pub fn from(arg: &T) -> Self {
200        Self {
201            status: Some(CODE_SUCCESS_I32),
202            message: None,
203            data: Some(arg.clone()),
204        }
205    }
206    pub fn from_message(data: &T, message: &str) -> Self {
207        Self {
208            status: Some(CODE_SUCCESS_I32),
209            message: Some(message.to_string()),
210            data: Some(data.clone()),
211        }
212    }
213    pub fn from_code_message(code: i32, message: &str, data: &T) -> Self {
214        Self {
215            status: Some(code),
216            message: Some(message.to_string()),
217            data: Some(data.clone()),
218        }
219    }
220
221    pub fn from_error(code: i32, message: &Error) -> Self {
222        // let mut code_str = code.to_string();
223        // if code_str.is_empty() {
224        //     code_str = CODE_FAIL.to_string();
225        // }
226        Self {
227            status: Some(code),
228            message: Some(message.to_string()),
229            data: None,
230        }
231    }
232
233    pub fn from_error_info(code: i32, message: &str) -> Self {
234        // let mut code_str = code.to_string();
235        // if code_str.is_empty() {
236        //     code_str = CODE_FAIL.to_string();
237        // }
238        Self {
239            status: Some(code),
240            message: Some(message.to_string()),
241            data: None,
242        }
243    }
244
245    pub fn resp_json(&self) -> Self {
246        Self {
247            status: self.status.clone(),
248            data: self.data.clone(),
249            message: self.message.clone()
250        }
251    }
252}
253
254impl<T> ToString for ResultDTO<T>
255where
256    T: Serialize + DeserializeOwned + Clone,
257{
258    fn to_string(&self) -> String {
259        serde_json::to_string(self).unwrap()
260    }
261}
262