Skip to main content

api_bones_test/builders/
response.rs

1use api_bones::links::Links;
2use api_bones::response::{ApiResponse, ResponseMeta};
3use chrono::Utc;
4use uuid::Uuid;
5
6/// Builder for a fake [`ApiResponse<T>`].
7///
8/// # Quick start
9///
10/// ```rust
11/// use api_bones_test::builders::FakeApiResponse;
12///
13/// let resp = FakeApiResponse::new("hello").build();
14/// assert_eq!(resp.data, "hello");
15/// assert!(resp.meta.request_id.is_some());
16/// assert!(resp.meta.timestamp.is_some());
17/// ```
18pub struct FakeApiResponse<T> {
19    data: T,
20    meta: Option<ResponseMeta>,
21    links: Option<Links>,
22    request_id: Option<String>,
23}
24
25impl<T> FakeApiResponse<T> {
26    #[must_use]
27    pub fn new(data: T) -> Self {
28        Self {
29            data,
30            meta: None,
31            links: None,
32            request_id: None,
33        }
34    }
35
36    #[must_use]
37    pub fn with_meta(mut self, meta: ResponseMeta) -> Self {
38        self.meta = Some(meta);
39        self
40    }
41
42    #[must_use]
43    pub fn with_links(mut self, links: Links) -> Self {
44        self.links = Some(links);
45        self
46    }
47
48    #[must_use]
49    pub fn with_request_id(mut self, id: impl Into<String>) -> Self {
50        self.request_id = Some(id.into());
51        self
52    }
53
54    #[must_use]
55    pub fn build(self) -> ApiResponse<T> {
56        let request_id = self
57            .request_id
58            .unwrap_or_else(|| Uuid::new_v4().to_string());
59        let meta = self.meta.unwrap_or_else(|| {
60            ResponseMeta::new()
61                .request_id(request_id)
62                .timestamp(Utc::now())
63        });
64        let mut builder = ApiResponse::builder(self.data).meta(meta);
65        if let Some(links) = self.links {
66            builder = builder.links(links);
67        }
68        builder.build()
69    }
70}