daoyi_cloud_common/models/
common_result.rs1use salvo::oapi;
2use salvo::prelude::*;
3use serde::Serialize;
4#[derive(Serialize, Clone, Debug)]
6pub struct CommonResult<T> {
7 pub code: i32,
9 pub msg: String,
11 pub data: Option<T>,
13}
14
15impl<T> CommonResult<T> {
16 pub fn ok(data: Option<T>) -> Self {
17 Self {
18 code: 0,
19 msg: "success".to_string(),
20 data,
21 }
22 }
23
24 pub fn err(code: i32, msg: String) -> Self {
25 Self {
26 code,
27 msg,
28 data: None,
29 }
30 }
31
32 pub fn empty_ok() -> Self {
33 Self {
34 code: 0,
35 msg: "success".to_string(),
36 data: None,
37 }
38 }
39}
40
41#[async_trait]
42impl<T> Writer for CommonResult<T>
43where
44 T: Serialize + Send + 'static,
45{
46 async fn write(self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
47 res.render(Json(self));
48 }
49}
50impl<T> oapi::ToResponse for CommonResult<T>
51where
52 T: oapi::ToSchema,
53{
54 fn to_response(components: &mut oapi::Components) -> oapi::RefOr<oapi::Response> {
55 let schema_ref = T::to_schema(components);
56 let response = oapi::Response::new("CommonResult response returns CommonResult entity")
57 .add_content(
58 "application/json",
59 oapi::Content::new(
60 oapi::Object::new()
61 .property(
62 "code",
63 oapi::Object::new()
64 .description("返回码")
65 .schema_type(oapi::schema::SchemaType::basic(
66 oapi::schema::BasicType::Integer,
67 ))
68 .format(oapi::SchemaFormat::KnownFormat(oapi::KnownFormat::Int32))
69 .example(0),
70 )
71 .required("code")
72 .property(
73 "msg",
74 oapi::Object::new()
75 .description("返回信息")
76 .schema_type(oapi::schema::SchemaType::basic(
77 oapi::schema::BasicType::String,
78 ))
79 .format(oapi::SchemaFormat::KnownFormat(oapi::KnownFormat::String))
80 .example("success"),
81 )
82 .required("msg")
83 .property("data", schema_ref),
84 ),
85 );
86 components.responses.insert("CommonResult", response);
87 oapi::RefOr::Ref(oapi::Ref::new(format!(
88 "#/components/responses/{}",
89 "CommonResult"
90 )))
91 }
92}
93impl<T> EndpointOutRegister for CommonResult<T>
94where
95 T: oapi::ToSchema,
96{
97 fn register(components: &mut oapi::Components, operation: &mut oapi::Operation) {
98 operation
99 .responses
100 .insert("200", <Self as oapi::ToResponse>::to_response(components))
101 }
102}