kiteconnect_async_wasm/models/common/
response.rs1use serde::{Deserialize, Serialize};
16use serde_json::Value as JsonValue;
17
18use super::errors::{KiteError, KiteResult};
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct KiteResponse<T> {
23 pub status: String,
25
26 pub data: Option<T>,
28
29 #[serde(default)]
31 pub message: String,
32
33 #[serde(default)]
35 pub error_type: Option<String>,
36}
37
38impl<T> KiteResponse<T> {
39 pub fn success(data: T) -> Self {
41 Self {
42 status: "success".to_string(),
43 data: Some(data),
44 message: String::new(),
45 error_type: None,
46 }
47 }
48
49 pub fn error(message: impl Into<String>, error_type: Option<String>) -> Self {
51 Self {
52 status: "error".to_string(),
53 data: None,
54 message: message.into(),
55 error_type,
56 }
57 }
58
59 pub fn is_success(&self) -> bool {
61 self.status == "success"
62 }
63
64 pub fn is_error(&self) -> bool {
66 self.status == "error"
67 }
68
69 pub fn into_result(self) -> KiteResult<T> {
71 match self.status.as_str() {
72 "success" => self
73 .data
74 .ok_or_else(|| KiteError::general("Success response missing data")),
75 "error" => Err(KiteError::api_error_with_type(
76 self.status,
77 self.message,
78 self.error_type.unwrap_or_default(),
79 )),
80 _ => Err(KiteError::general(format!(
81 "Unknown response status: {}",
82 self.status
83 ))),
84 }
85 }
86}
87
88#[derive(Debug, Clone, Serialize, Deserialize)]
90pub struct RawResponse {
91 pub status: String,
93
94 pub data: Option<JsonValue>,
96
97 #[serde(default)]
99 pub message: String,
100
101 #[serde(default)]
103 pub error_type: Option<String>,
104}
105
106impl From<RawResponse> for KiteResponse<JsonValue> {
107 fn from(raw: RawResponse) -> Self {
108 Self {
109 status: raw.status,
110 data: raw.data,
111 message: raw.message,
112 error_type: raw.error_type,
113 }
114 }
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(rename_all = "lowercase")]
120pub enum Status {
121 Success,
122 Error,
123}
124
125impl Status {
126 pub fn is_success(self) -> bool {
127 matches!(self, Status::Success)
128 }
129
130 pub fn is_error(self) -> bool {
131 matches!(self, Status::Error)
132 }
133}
134
135impl From<String> for Status {
136 fn from(s: String) -> Self {
137 match s.to_lowercase().as_str() {
138 "success" => Status::Success,
139 "error" => Status::Error,
140 _ => Status::Error, }
142 }
143}
144
145impl From<&str> for Status {
146 fn from(s: &str) -> Self {
147 Self::from(s.to_string())
148 }
149}