toolcraft_axum_kit/
response.rs1use core::str;
2
3use axum::{Json, http::StatusCode};
4use serde::Serialize;
5use utoipa::ToSchema;
6
7#[derive(Debug, Serialize, ToSchema, Default, Clone)]
8pub struct Empty;
9
10pub type CommonOk = CommonResponse<Empty>;
11
12pub trait IntoCommonResponse<T>
13where
14 T: Serialize + ToSchema,
15{
16 fn into_common_response(self) -> CommonResponse<T>;
17}
18
19impl<T> IntoCommonResponse<T> for T
20where
21 T: Serialize + ToSchema,
22{
23 fn into_common_response(self) -> CommonResponse<T> {
24 CommonResponse {
25 code: 0,
26 data: self,
27 message: String::from("Success"),
28 }
29 }
30}
31
32#[derive(Debug, Serialize, ToSchema)]
33pub struct CommonResponse<T>
34where
35 T: Serialize + ToSchema,
36{
37 pub code: i16,
38 pub data: T,
39 pub message: String,
40}
41
42impl<T> CommonResponse<T>
43where
44 T: Serialize + ToSchema,
45{
46 pub fn to_json(self) -> Json<Self> {
47 Json(self)
48 }
49}
50
51impl<T> Default for CommonResponse<T>
52where
53 T: Serialize + ToSchema + Default,
54{
55 fn default() -> Self {
56 CommonResponse {
57 code: 0,
58 data: T::default(),
59 message: String::from("Success"),
60 }
61 }
62}
63
64#[derive(Debug, Serialize, ToSchema)]
65pub struct CommonError {
66 pub code: i16,
67 pub message: String,
68}
69
70impl CommonError {
71 pub fn to_json(self) -> Json<Self> {
72 Json(self)
73 }
74}
75
76impl From<(i16, &str)> for CommonError {
77 fn from(value: (i16, &str)) -> Self {
78 CommonError {
79 code: value.0,
80 message: value.1.to_string(),
81 }
82 }
83}
84
85pub type ResponseResult<T> =
86 core::result::Result<Json<CommonResponse<T>>, (StatusCode, Json<CommonError>)>;
87pub type Result<T> = core::result::Result<T, (StatusCode, Json<CommonError>)>;