use std::collections::HashMap; use chrono::{Local, DateTime}; use serde::{Deserialize, Serialize}; use serde_json::Value; #[derive(Serialize, Deserialize)] pub struct RespObject { respCode: String, // 返回该次请求状态code errorCode: i32, respMessage: String, // 消息内容 respBody: Value, respList: Vec, /// 封装好的返回对象数据模型(可能是json对象或者json数组,亦或者是一个value) itemCount: i32, serverDate: DateTime, } pub struct RespObjectBuilder { respCode: String, // 返回该次请求状态code errorCode: i32, respMessage: String, // 消息内容 respBody: Value, respList: Vec, /// 封装好的返回对象数据模型(可能是json对象或者json数组,亦或者是一个value) itemCount: i32, serverDate: DateTime, body: HashMap, } impl RespObjectBuilder { pub fn add_result(&mut self, key: String, val: Value) -> &mut Self { self.body.insert(key, val); self } pub fn respCode(&mut self, respCode: String) -> &mut Self { self.respCode = respCode; self } pub fn errorCode(&mut self, errorCode: i32) -> &mut Self { self.errorCode = errorCode; self } pub fn respMessage(&mut self, respMessage: String) -> &mut Self { self.respMessage = respMessage; self } pub fn respBody(&mut self, respBody: Value) -> &mut Self { self.respBody = respBody; self } pub fn respList(&mut self, respList: Vec) -> &mut Self { self.respList = respList; self } pub fn itemCount(&mut self, itemCount: i32) -> &mut Self { self.itemCount = itemCount; self } pub fn build(self) -> RespObject { let mut obj = RespObject::::default(); let respBody = if self.respBody.is_null() && !self.body.is_empty() { serde_json::to_value(self.body).unwrap() } else { Value::Null }; RespObject { respCode: self.respCode, errorCode: 0, respMessage: self.respMessage, respBody, respList: self.respList, itemCount: self.itemCount, serverDate: Local::now(), } } } impl RespObject { const SUCCESS: &'static str = "success"; const ERROR: &'static str = "error"; // session超时 const TIMEOUT: &'static str = "mzywx_app_session_timeout"; const FATAL_ERROR: &'static str = "fatalError"; const WARNING: &'static str = "warning"; pub fn success(respBody:Value) -> Self { Self { respBody, ..Self::default() } } pub fn err(respMessage: String) -> RespObject { Self { respMessage, ..Self::default() } } pub fn builder() -> RespObjectBuilder { RespObjectBuilder { respCode: Self::SUCCESS.to_string(), errorCode: 0, respMessage: "".to_string(), respBody: Value::Null, respList: vec![], itemCount: 0, serverDate: Local::now(), body: HashMap::new(), } } } impl Default for RespObject { fn default() -> Self { Self { respCode: Self::SUCCESS.to_string(), errorCode: 0, respMessage: "".to_string(), respBody: Value::Null, respList: vec![], itemCount: 0, serverDate: Local::now(), } } }