Skip to main content

ironflow_api/
response.rs

1//! Standard response types and helpers for the REST API.
2//!
3//! All successful responses are wrapped in the [`ApiResponse`] envelope
4//! with optional pagination metadata.
5
6use axum::Json;
7use serde::Serialize;
8
9pub use ironflow_types::{ApiMeta, ApiResponse, ErrorEnvelope};
10
11/// Helper to wrap data in a successful response without pagination.
12///
13/// # Examples
14///
15/// ```no_run
16/// use ironflow_api::response::ok;
17///
18/// # async fn handler() {
19/// let data = vec!["a", "b"];
20/// let response = ok(data);
21/// // Returns: { "data": ["a", "b"] }
22/// # }
23/// ```
24pub fn ok<T: Serialize>(data: T) -> Json<ApiResponse<T>> {
25    Json(ApiResponse { data, meta: None })
26}
27
28/// Helper to wrap paginated data in a successful response.
29///
30/// # Examples
31///
32/// ```no_run
33/// use ironflow_api::response::ok_paged;
34///
35/// # async fn handler() {
36/// let data = vec!["a", "b"];
37/// let response = ok_paged(data, 1, 20, 100);
38/// // Returns: { "data": ["a", "b"], "meta": { "page": 1, "per_page": 20, "total": 100 } }
39/// # }
40/// ```
41pub fn ok_paged<T: Serialize>(
42    data: T,
43    page: u32,
44    per_page: u32,
45    total: u64,
46) -> Json<ApiResponse<T>> {
47    Json(ApiResponse {
48        data,
49        meta: Some(ApiMeta::paginated(page, per_page, total)),
50    })
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56    use serde_json::json;
57
58    #[test]
59    fn ok_wraps_data_without_meta() {
60        let Json(response) = ok(vec![1, 2, 3]);
61        let json_val = serde_json::to_value(&response).expect("serialize");
62        assert_eq!(json_val["data"], json!([1, 2, 3]));
63        assert_eq!(json_val["meta"], json!(null));
64    }
65
66    #[test]
67    fn ok_paged_wraps_data_with_pagination() {
68        let Json(response) = ok_paged(vec!["a", "b"], 2, 20, 100);
69        let json_val = serde_json::to_value(&response).expect("serialize");
70        assert_eq!(json_val["data"], json!(["a", "b"]));
71        assert_eq!(json_val["meta"]["page"], 2);
72        assert_eq!(json_val["meta"]["per_page"], 20);
73        assert_eq!(json_val["meta"]["total"], 100);
74    }
75}