use std::fmt::{Display, };
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::rubase::{BaseEntity};
use crate::rubase::get_self::GetSelf;
#[derive(Serialize, Deserialize, Default,Debug, Clone, PartialEq, Eq)]
pub struct RuResult {
#[serde(skip_serializing_if = "is_zero_code")]
pub code: i32,
#[serde(skip_serializing_if = "String::is_empty")]
pub msg: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<Value>,
pub exist: bool,
}
fn is_zero_code(code: &i32) -> bool { *code == 0 }
impl BaseEntity for RuResult {
}
impl GetSelf for RuResult {
}
impl RuResult {
pub fn new() -> Self {
Self {
code: 200,
msg: "成功".to_string(),
data: None,
exist: false,
}
}
pub fn newFail() -> Self {
Self {
code: 500,
msg: "失败".to_string(),
data: None,
exist: false,
}
}
pub fn is_success(&self) -> bool {
self.code == 200 || self.code == 0
}
pub fn is_failed(&self) -> bool {
!self.is_success()
}
}
impl RuResult {
pub fn success_data(data: Value) -> Self {
Self { code: 200, msg: "成功".to_string(), data: Some(data), exist: true }
}
pub fn success() -> Self {
Self { code: 200, msg: "成功".to_string(), data: None, exist: false }
}
pub fn fail(msg: &str) -> Self {
Self { code: 500, msg: msg.to_string(), data: None, exist: false }
}
pub fn from_error(err: &dyn std::error::Error) -> Self {
Self { code: 500, msg: err.to_string(), data: None, exist: false }
}
pub fn from (code: i32, msg: &str) -> Self {
Self { code, msg: msg.to_string(), data: None, exist: false }
}
pub fn set_data(&mut self, data: Value) {
self.data = Some(data);
self.exist = true;
}
pub fn set_code_msg(&mut self, code: i32, msg: &str) {
self.code = code;
self.msg = msg.to_string();
self.data = None;
self.exist = false;
}
pub fn get_code(&self) -> i32 {
self.code
}
pub fn get_msg(&self) -> String {
self.msg.to_string()
}
}