routerify_json_response/
success_resp.rs

1use crate::gen_resp::gen_response;
2use http::{Response, StatusCode};
3use http_body::Body as HttpBody;
4use serde::Serialize;
5
6const STATUS_SUCCESS: &'static str = "success";
7
8#[derive(Serialize, Debug, Clone)]
9#[serde(rename_all = "camelCase")]
10struct SuccessResp<'a, D>
11where
12    D: Serialize + Send + Sync + Unpin,
13{
14    status: &'static str,
15    code: u16,
16    data: &'a D,
17}
18
19/// Generates a success JSON response with the provided data and the status code.
20///
21/// It generates JSON response in the following JSON format:
22///
23///  ```json
24///  {
25///      "status": "success",
26///      "code": "<status_code>",
27///      "data": "<data>"
28///  }
29///```
30///
31/// # Examples
32///
33/// ```
34/// use hyper::{Body, Request, Response, StatusCode};
35/// use routerify_json_response::{json_success_resp_with_code};
36///
37/// async fn list_users_handler(_: Request<Body>) -> Result<Response<Body>, routerify_json_response::Error> {
38///     // Fetch response data from somewhere.
39///     let users = ["Alice", "John"];
40///
41///     // Generate a success JSON response with the data in the following format:
42///     // { "status": "success", code: 201, data: ["Alice", "John"] }
43///     json_success_resp_with_code(StatusCode::CREATED, &users)
44/// }
45/// ```
46pub fn json_success_resp_with_code<B, D>(code: StatusCode, data: &D) -> crate::Result<Response<B>>
47where
48    B: HttpBody + From<Vec<u8>> + Send + Sync + Unpin + 'static,
49    D: Serialize + Send + Sync + Unpin,
50{
51    let resp_data = SuccessResp {
52        status: STATUS_SUCCESS,
53        code: code.as_u16(),
54        data,
55    };
56
57    gen_response(code, &resp_data)
58}
59
60/// Generates a success JSON response with the provided data and the `OK 200` status code.
61///
62/// It generates JSON response in the following JSON format:
63///
64///  ```json
65///  {
66///      "status": "success",
67///      "code": "200",
68///      "data": "<data>"
69///  }
70///```
71///
72/// # Examples
73///
74/// ```
75/// use hyper::{Body, Request, Response, StatusCode};
76/// use routerify_json_response::{json_success_resp};
77///
78/// async fn list_users_handler(_: Request<Body>) -> Result<Response<Body>, routerify_json_response::Error> {
79///     // Fetch response data from somewhere.
80///     let users = ["Alice", "John"];
81///
82///     // Generate a success JSON response with the data in the following format:
83///     // { "status": "success", code: 200, data: ["Alice", "John"] }
84///     json_success_resp(&users)
85/// }
86/// ```
87pub fn json_success_resp<B, D>(data: &D) -> crate::Result<Response<B>>
88where
89    B: HttpBody + From<Vec<u8>> + Send + Sync + Unpin + 'static,
90    D: Serialize + Send + Sync + Unpin,
91{
92    json_success_resp_with_code::<B, D>(StatusCode::OK, data)
93}