Skip to main content

api_bones_test/builders/
paginated.rs

1use api_bones::pagination::PaginatedResponse;
2
3/// Builder for a fake [`PaginatedResponse<T>`].
4///
5/// # Quick start
6///
7/// ```rust
8/// use api_bones_test::builders::FakePaginated;
9///
10/// let resp = FakePaginated::new(vec![1u32, 2, 3]).build();
11/// assert_eq!(resp.items.len(), 3);
12/// assert_eq!(resp.total_count, 3);
13/// assert_eq!(resp.limit, 3);
14/// assert_eq!(resp.offset, 0);
15/// assert!(!resp.has_more);
16/// ```
17pub struct FakePaginated<T> {
18    items: Vec<T>,
19    total: Option<u64>,
20    limit: Option<u64>,
21    offset: u64,
22    has_more: Option<bool>,
23}
24
25impl<T> FakePaginated<T> {
26    #[must_use]
27    pub fn new(items: Vec<T>) -> Self {
28        Self {
29            items,
30            total: None,
31            limit: None,
32            offset: 0,
33            has_more: None,
34        }
35    }
36
37    #[must_use]
38    pub fn total(mut self, total: u64) -> Self {
39        self.total = Some(total);
40        self
41    }
42
43    #[must_use]
44    pub fn limit(mut self, limit: u64) -> Self {
45        self.limit = Some(limit);
46        self
47    }
48
49    #[must_use]
50    pub fn offset(mut self, offset: u64) -> Self {
51        self.offset = offset;
52        self
53    }
54
55    #[must_use]
56    pub fn has_more(mut self, has_more: bool) -> Self {
57        self.has_more = Some(has_more);
58        self
59    }
60
61    #[must_use]
62    pub fn build(self) -> PaginatedResponse<T> {
63        let count = self.items.len() as u64;
64        let total = self.total.unwrap_or(count);
65        let limit = self.limit.unwrap_or(count);
66        let has_more = self.has_more.unwrap_or_else(|| self.offset + count < total);
67        PaginatedResponse {
68            items: self.items,
69            total_count: total,
70            has_more,
71            limit,
72            offset: self.offset,
73        }
74    }
75}