use std::fmt::Display;
use axum::response::Response;
use serde::{Deserialize, Serialize};
use serde::de::DeserializeOwned;
use crate::error::Error;
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
#[serde(rename_all = "camelCase")]
pub struct ServiceResponse<T> {
pub error_code: i32,
pub error_msg: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<T>,
}
impl<T> ServiceResponse<T> where T: Serialize + DeserializeOwned + Clone, {
pub fn result(arg: &Result<T, Error>) -> Self {
match arg {
Ok(data) => Self {
error_code: 0,
error_msg: "ok".to_string(),
data: Some(data.clone()),
},
Err(e) => Self {
error_code: e.error_code,
error_msg: e.error_msg.clone(),
data: None,
},
}
}
pub fn to_response_json(&self) -> Response<String> {
axum::response::Response::builder()
.header("Content-Type", "text/json;charset=UTF-8")
.header("Cache-Control", "no-cache")
.body(self.to_string()).unwrap()
}
}
impl<T> Display for ServiceResponse<T> where T: Serialize + DeserializeOwned + Clone,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", serde_json::to_string(self).unwrap())
}
}