forge_core_utils/
response.rs

1use serde::{Deserialize, Serialize};
2use ts_rs_forge::TS;
3
4#[derive(Debug, Serialize, Deserialize, TS)]
5pub struct ApiResponse<T, E = T> {
6    success: bool,
7    data: Option<T>,
8    error_data: Option<E>,
9    message: Option<String>,
10}
11
12impl<T, E> ApiResponse<T, E> {
13    /// Creates a successful response, with `data` and no message.
14    pub fn success(data: T) -> Self {
15        ApiResponse {
16            success: true,
17            data: Some(data),
18            message: None,
19            error_data: None,
20        }
21    }
22
23    /// Creates an error response, with `message` and no data.
24    pub fn error(message: &str) -> Self {
25        ApiResponse {
26            success: false,
27            data: None,
28            message: Some(message.to_string()),
29            error_data: None,
30        }
31    }
32    /// Creates an error response, with no `data`, no `message`, but with arbitrary `error_data`.
33    pub fn error_with_data(data: E) -> Self {
34        ApiResponse {
35            success: false,
36            data: None,
37            error_data: Some(data),
38            message: None,
39        }
40    }
41
42    /// Returns true if the response was successful.
43    pub fn is_success(&self) -> bool {
44        self.success
45    }
46
47    /// Consumes the response and returns the data if present.
48    pub fn into_data(self) -> Option<T> {
49        self.data
50    }
51
52    /// Returns a reference to the error message if present.
53    pub fn message(&self) -> Option<&str> {
54        self.message.as_deref()
55    }
56}