Skip to main content

fusion_common/model/
result.rs

1use serde::{Deserialize, Serialize, de::DeserializeOwned};
2
3/// 能用包装结果,将可 Serialize 的类型包裹在 `data` 字段中
4#[derive(Debug, Serialize, Deserialize)]
5#[cfg_attr(feature = "with-openapi", derive(utoipa::ToSchema))]
6pub struct WrapperResult<T> {
7  pub data: T,
8}
9
10impl<T> WrapperResult<T> {
11  pub fn new(data: T) -> Self {
12    Self { data }
13  }
14}
15
16impl<T: Serialize> From<T> for WrapperResult<T> {
17  fn from(data: T) -> Self {
18    Self::new(data)
19  }
20}
21
22#[derive(Debug, Serialize, Deserialize)]
23#[cfg_attr(feature = "with-openapi", derive(utoipa::ToSchema))]
24pub struct IdResult {
25  pub id: serde_json::Value,
26}
27
28impl IdResult {
29  pub fn new<T>(id: T) -> Self
30  where
31    T: Serialize,
32  {
33    Self { id: serde_json::to_value(id).unwrap() }
34  }
35
36  pub fn to<T>(&self) -> Result<T, serde_json::Error>
37  where
38    T: DeserializeOwned,
39  {
40    serde_json::from_value(self.id.clone())
41  }
42
43  #[cfg(feature = "with-uuid")]
44  pub fn to_uuid(&self) -> Result<uuid::Uuid, serde_json::Error> {
45    self.to::<uuid::Uuid>()
46  }
47}
48
49#[derive(Debug, Serialize, Deserialize)]
50#[cfg_attr(feature = "with-openapi", derive(utoipa::ToSchema))]
51pub struct IdI64Result {
52  pub id: i64,
53}
54impl IdI64Result {
55  pub fn new(id: i64) -> Self {
56    Self { id }
57  }
58}
59
60#[derive(Debug, Serialize, Deserialize)]
61#[cfg_attr(feature = "with-openapi", derive(utoipa::ToSchema))]
62pub struct IdStringResult {
63  pub id: String,
64}
65impl IdStringResult {
66  pub fn new(id: String) -> Self {
67    Self { id }
68  }
69}
70
71#[cfg(feature = "with-uuid")]
72#[derive(Debug, Serialize, Deserialize)]
73#[cfg_attr(feature = "with-openapi", derive(utoipa::ToSchema))]
74pub struct IdUuidResult {
75  pub id: uuid::Uuid,
76}
77
78#[cfg(feature = "with-uuid")]
79impl IdUuidResult {
80  pub fn new(id: uuid::Uuid) -> Self {
81    Self { id }
82  }
83}
84
85#[cfg(feature = "with-uuid")]
86impl From<uuid::Uuid> for IdUuidResult {
87  fn from(id: uuid::Uuid) -> Self {
88    Self::new(id)
89  }
90}
91
92#[cfg(feature = "with-ulid")]
93#[derive(Debug, Serialize, Deserialize)]
94#[cfg_attr(feature = "with-openapi", derive(utoipa::ToSchema))]
95pub struct IdUlidResult {
96  pub id: ulid::Ulid,
97}
98
99#[cfg(feature = "with-ulid")]
100impl IdUlidResult {
101  pub fn new(id: ulid::Ulid) -> Self {
102    Self { id }
103  }
104}