mycommon_utils/model/
response.rs1use std::fmt::Display;
2use axum::response::Response;
3use serde::{Deserialize, Serialize};
4use serde::de::DeserializeOwned;
5use crate::error::Error;
6
7#[derive(Debug, Serialize, Deserialize, Clone, Default)]
9#[serde(rename_all = "camelCase")]
10pub struct ServiceResponse<T> {
11 pub error_code: i32,
12 pub error_msg: String,
13 #[serde(skip_serializing_if = "Option::is_none")]
14 pub data: Option<T>,
15}
16
17impl<T> ServiceResponse<T> where T: Serialize + DeserializeOwned + Clone, {
18 pub fn result(arg: &Result<T, Error>) -> Self {
19 match arg {
20 Ok(data) => Self {
21 error_code: 0,
22 error_msg: "ok".to_string(),
23 data: Some(data.clone()),
24 },
25 Err(e) => Self {
26 error_code: e.error_code,
27 error_msg: e.error_msg.clone(),
28 data: None,
29 },
30 }
31 }
32
33 pub fn to_response_json(&self) -> Response<String> {
34 axum::response::Response::builder()
35 .header("Content-Type", "text/json;charset=UTF-8")
36 .header("Cache-Control", "no-cache")
37 .body(self.to_string()).unwrap()
38 }
39}
40
41impl<T> Display for ServiceResponse<T> where T: Serialize + DeserializeOwned + Clone,
42{
43 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44 write!(f, "{}", serde_json::to_string(self).unwrap())
45 }
46}