use std::fmt;
use displaydoc::Display;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::rubase::ruentity;
use crate::rubase::rutils::jsonutils;
use crate::rulog::rulog;
#[derive(Serialize, Deserialize, 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 ruentity::BaseEntity for RuResult {
}
impl fmt::Display for RuResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let ret = jsonutils::struct2json(&self);
match ret {
Ok(data) => {
rulog::info(data.as_str() );
Ok(())
}
Err(e) => {
eprintln!("JSON 解析失败: {}", e);
Err(fmt::Error) }
}
}
}
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 }
}
}