1use crate::pagination::ResultPagination;
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11#[repr(i32)]
12#[non_exhaustive]
13pub enum ErrorCode {
14 Success = 0,
15 BadRequest = 400,
16 Unauthorized = 401,
17 Forbidden = 403,
18 NotFound = 404,
19 MethodNotAllowed = 405,
20 Conflict = 409,
21 PayloadTooLarge = 413,
22 ValidationError = 422,
23 TooManyRequests = 429,
24 InternalError = 500,
25 ServiceUnavailable = 503,
26}
27
28impl ErrorCode {
29 pub fn as_i32(self) -> i32 {
31 self as i32
32 }
33
34 pub fn as_str(self) -> &'static str {
36 match self {
37 ErrorCode::Success => "Success",
38 ErrorCode::BadRequest => "Bad Request",
39 ErrorCode::Unauthorized => "Unauthorized",
40 ErrorCode::Forbidden => "Forbidden",
41 ErrorCode::NotFound => "Not Found",
42 ErrorCode::MethodNotAllowed => "Method Not Allowed",
43 ErrorCode::Conflict => "Conflict",
44 ErrorCode::PayloadTooLarge => "Payload Too Large",
45 ErrorCode::ValidationError => "Unprocessable Entity",
46 ErrorCode::TooManyRequests => "Too Many Requests",
47 ErrorCode::InternalError => "Internal Server Error",
48 ErrorCode::ServiceUnavailable => "Service Unavailable",
49 }
50 }
51
52 pub fn from_i32(value: i32) -> Option<Self> {
54 match value {
55 0 => Some(ErrorCode::Success),
56 400 => Some(ErrorCode::BadRequest),
57 401 => Some(ErrorCode::Unauthorized),
58 403 => Some(ErrorCode::Forbidden),
59 404 => Some(ErrorCode::NotFound),
60 405 => Some(ErrorCode::MethodNotAllowed),
61 409 => Some(ErrorCode::Conflict),
62 413 => Some(ErrorCode::PayloadTooLarge),
63 422 => Some(ErrorCode::ValidationError),
64 429 => Some(ErrorCode::TooManyRequests),
65 500 => Some(ErrorCode::InternalError),
66 503 => Some(ErrorCode::ServiceUnavailable),
67 _ => None,
68 }
69 }
70}
71
72#[derive(Debug, Clone, Serialize, Deserialize)]
78#[cfg_attr(not(feature = "snake-case"), serde(rename_all = "camelCase"))]
79#[cfg_attr(feature = "snake-case", serde(rename_all = "snake_case"))]
80pub struct FieldError {
81 pub field: String,
82 pub message: String,
83}
84
85impl FieldError {
86 pub fn new(field: impl Into<String>, message: impl Into<String>) -> Self {
87 Self {
88 field: field.into(),
89 message: message.into(),
90 }
91 }
92}
93
94#[derive(Debug, Clone, Serialize, Deserialize, Default)]
100#[serde(untagged)]
101#[non_exhaustive]
102pub enum ResponseData<T> {
103 Single(T),
105 Multiple(Vec<T>),
107 #[default]
109 Empty,
110}
111
112impl<T> ResponseData<T> {
113 pub fn single(v: T) -> Self {
115 ResponseData::Single(v)
116 }
117
118 pub fn multiple(v: Vec<T>) -> Self {
120 ResponseData::Multiple(v)
121 }
122
123 pub fn is_single(&self) -> bool {
125 matches!(self, ResponseData::Single(_))
126 }
127
128 pub fn is_multiple(&self) -> bool {
130 matches!(self, ResponseData::Multiple(_))
131 }
132
133 pub fn is_empty(&self) -> bool {
135 matches!(self, ResponseData::Empty)
136 }
137
138 pub fn as_single(&self) -> Option<&T> {
140 match self {
141 ResponseData::Single(v) => Some(v),
142 _ => None,
143 }
144 }
145
146 pub fn as_multiple(&self) -> Option<&Vec<T>> {
148 match self {
149 ResponseData::Multiple(v) => Some(v),
150 _ => None,
151 }
152 }
153
154 #[inline]
156 pub fn len(&self) -> usize {
157 match self {
158 ResponseData::Single(_) => 1,
159 ResponseData::Multiple(v) => v.len(),
160 ResponseData::Empty => 0,
161 }
162 }
163
164 #[inline]
169 #[allow(clippy::len_zero)]
170 pub fn is_empty_data(&self) -> bool {
171 self.len() == 0
172 }
173}
174
175impl<T> From<T> for ResponseData<T> {
176 fn from(v: T) -> Self {
177 ResponseData::Single(v)
178 }
179}
180
181impl<T> From<Vec<T>> for ResponseData<T> {
182 fn from(v: Vec<T>) -> Self {
183 ResponseData::Multiple(v)
184 }
185}
186
187#[derive(Debug, Clone, Serialize, Deserialize)]
193#[cfg_attr(not(feature = "snake-case"), serde(rename_all = "camelCase"))]
194#[cfg_attr(feature = "snake-case", serde(rename_all = "snake_case"))]
195pub struct ApiResult<T> {
196 pub success: bool,
197 #[serde(skip_serializing_if = "Option::is_none")]
198 pub data: Option<ResponseData<T>>,
199 #[serde(skip_serializing_if = "Option::is_none")]
200 pub message: Option<String>,
201 #[serde(skip_serializing_if = "Option::is_none")]
202 pub code: Option<i32>,
203 #[serde(skip_serializing_if = "Option::is_none")]
204 pub pagination: Option<ResultPagination>,
205 #[serde(skip_serializing_if = "Option::is_none")]
206 pub errors: Option<Vec<FieldError>>,
207 #[serde(skip_serializing_if = "Option::is_none")]
208 pub trace_id: Option<String>,
209 #[serde(skip_serializing_if = "Option::is_none")]
210 pub biz_code: Option<i32>,
211 #[serde(skip_serializing_if = "Option::is_none")]
212 pub timestamp: Option<i64>,
213 #[serde(skip_serializing_if = "Option::is_none")]
214 pub extra: Option<Value>,
215}
216
217impl<T> ApiResult<T> {
218 #[inline]
222 fn new(
223 success: bool,
224 data: Option<ResponseData<T>>,
225 message: Option<String>,
226 code: Option<i32>,
227 ) -> Self {
228 ApiResult {
229 success,
230 data,
231 message,
232 code,
233 pagination: None,
234 errors: None,
235 trace_id: None,
236 biz_code: None,
237 timestamp: None,
238 extra: None,
239 }
240 }
241
242 #[inline]
246 pub fn value(v: T) -> Self {
247 Self::new(true, Some(ResponseData::single(v)), None, None)
248 }
249
250 #[inline]
252 pub fn list(v: Vec<T>) -> Self {
253 Self::new(true, Some(ResponseData::multiple(v)), None, None)
254 }
255
256 #[inline]
258 pub fn fail(message: &str) -> Self {
259 Self::failure(message)
260 }
261
262 #[inline]
264 pub fn failure(message: &str) -> Self {
265 Self::new(false, None, Some(message.to_string()), None)
266 }
267
268 #[inline]
272 pub fn success() -> Self {
273 Self::ok()
274 }
275
276 #[inline]
278 pub fn ok() -> Self {
279 Self::new(true, None, None, None)
280 }
281
282 pub fn validation_errors(errors: Vec<FieldError>) -> Self {
284 let mut r = Self::new(
285 false,
286 None,
287 Some("Validation failed".to_string()),
288 Some(ErrorCode::ValidationError as i32),
289 );
290 r.errors = Some(errors);
291 r
292 }
293
294 pub fn from_result<E: std::fmt::Display>(result: Result<T, E>) -> Self {
296 match result {
297 Ok(data) => Self::value(data),
298 Err(err) => Self::new(
299 false,
300 None,
301 Some(err.to_string()),
302 Some(ErrorCode::InternalError as i32),
303 ),
304 }
305 }
306
307 #[inline]
311 pub fn is_success(&self) -> bool {
312 self.success
313 }
314
315 #[inline]
317 pub fn is_error(&self) -> bool {
318 !self.success
319 }
320
321 pub fn error_code(&self) -> Option<ErrorCode> {
323 if !self.success {
324 self.code.and_then(ErrorCode::from_i32)
325 } else {
326 None
327 }
328 }
329
330 #[inline]
334 pub fn with_extra(mut self, key: &str, value: Value) -> Self {
335 match self.extra {
336 Some(ref mut v) => {
337 v[key] = value;
338 }
339 None => {
340 let mut v = serde_json::Map::new();
341 v.insert(key.to_string(), value);
342 self.extra = Some(v.into());
343 }
344 }
345 self
346 }
347
348 #[inline]
350 pub fn with_code(mut self, code: i32) -> Self {
351 self.code = Some(code);
352 self
353 }
354
355 #[inline]
357 pub fn with_pagination(mut self, pagination: ResultPagination) -> Self {
358 self.pagination = Some(pagination);
359 self
360 }
361
362 #[inline]
364 pub fn with_message(mut self, message: &str) -> Self {
365 self.message = Some(message.to_string());
366 self
367 }
368
369 #[inline]
371 pub fn with_errors(mut self, errors: Vec<FieldError>) -> Self {
372 self.errors = Some(errors);
373 self
374 }
375
376 #[inline]
378 pub fn with_error(mut self, field: impl Into<String>, message: impl Into<String>) -> Self {
379 match self.errors {
380 Some(ref mut v) => v.push(FieldError::new(field, message)),
381 None => self.errors = Some(vec![FieldError::new(field, message)]),
382 }
383 self
384 }
385
386 #[inline]
388 pub fn with_trace_id(mut self, id: impl Into<String>) -> Self {
389 self.trace_id = Some(id.into());
390 self
391 }
392
393 #[inline]
395 pub fn with_biz_code(mut self, code: i32) -> Self {
396 self.biz_code = Some(code);
397 self
398 }
399
400 #[inline]
402 pub fn with_timestamp(mut self, ts: i64) -> Self {
403 self.timestamp = Some(ts);
404 self
405 }
406
407 pub fn with_current_timestamp(self) -> Self {
409 use std::time::{SystemTime, UNIX_EPOCH};
410 let ts = SystemTime::now()
411 .duration_since(UNIX_EPOCH)
412 .map(|d| d.as_millis() as i64)
413 .unwrap_or(0);
414 self.with_timestamp(ts)
415 }
416}
417
418impl<T, E> From<ApiResult<T>> for Result<ApiResult<T>, E> {
430 fn from(val: ApiResult<T>) -> Self {
431 Ok(val)
432 }
433}
434
435impl<T> From<anyhow::Error> for ApiResult<T> {
440 fn from(err: anyhow::Error) -> Self {
441 Self::new(
442 false,
443 None,
444 Some(err.to_string()),
445 Some(ErrorCode::InternalError as i32),
446 )
447 }
448}
449
450impl<T> From<std::io::Error> for ApiResult<T> {
451 fn from(err: std::io::Error) -> Self {
452 Self::new(
453 false,
454 None,
455 Some(err.to_string()),
456 Some(ErrorCode::InternalError as i32),
457 )
458 }
459}
460
461impl<T> From<std::string::FromUtf8Error> for ApiResult<T> {
462 fn from(err: std::string::FromUtf8Error) -> Self {
463 Self::new(
464 false,
465 None,
466 Some(err.to_string()),
467 Some(ErrorCode::InternalError as i32),
468 )
469 }
470}
471
472impl<T, E: std::fmt::Display + std::fmt::Debug> From<Result<T, E>> for ApiResult<T> {
474 fn from(result: Result<T, E>) -> Self {
475 match result {
476 Ok(data) => Self::value(data),
477 Err(err) => Self::new(
478 false,
479 None,
480 Some(format!("{}", err)),
481 Some(ErrorCode::InternalError as i32),
482 ),
483 }
484 }
485}
486
487pub type DefaultResult<T> = Result<T, Box<dyn std::error::Error>>;