json_response/
success_resp.rs

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