oparl_types/
pagination.rs

1// SPDX-FileCopyrightText: Politik im Blick developers
2// SPDX-FileCopyrightText: Wolfgang Silbermayr <wolfgang@silbermayr.at>
3//
4// SPDX-License-Identifier: AGPL-3.0-or-later OR EUPL-1.2
5
6#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
7#[serde(rename_all = "camelCase")]
8pub struct Pagination {
9    #[serde(default, skip_serializing_if = "Option::is_none")]
10    pub total_elements: Option<usize>,
11
12    #[serde(default, skip_serializing_if = "Option::is_none")]
13    pub elements_per_page: Option<usize>,
14
15    #[serde(default, skip_serializing_if = "Option::is_none")]
16    pub current_page: Option<usize>,
17
18    #[serde(default, skip_serializing_if = "Option::is_none")]
19    pub total_pages: Option<usize>,
20}
21
22#[cfg(test)]
23mod serde_tests {
24    use super::Pagination;
25
26    use pretty_assertions::assert_eq;
27    use serde_json::json;
28
29    fn example_pagination() -> Pagination {
30        Pagination {
31            total_elements: Some(50000),
32            elements_per_page: Some(100),
33            current_page: Some(3),
34            total_pages: Some(500),
35        }
36    }
37
38    fn example_pagination_json() -> serde_json::Value {
39        json!({
40        "totalElements": 50000,
41        "elementsPerPage": 100,
42        "currentPage": 3,
43        "totalPages":500})
44    }
45
46    #[test]
47    fn serialize() {
48        assert_eq!(json!(example_pagination()), example_pagination_json());
49    }
50
51    #[test]
52    fn deserialize_good() {
53        let deserialized: Pagination = serde_json::from_value(example_pagination_json())
54            .expect("value must be deserializable as Pagination");
55        assert_eq!(deserialized, example_pagination());
56    }
57
58    #[test]
59    fn serialize_empty() {
60        assert_eq!(
61            json!(Pagination {
62                total_elements: None,
63                elements_per_page: None,
64                current_page: None,
65                total_pages: None
66            }),
67            json!({}),
68        );
69    }
70
71    #[test]
72    fn deserialize_empty() {
73        let deserialized: Pagination =
74            serde_json::from_value(json!({})).expect("value must be deserializable as Pagination");
75        assert_eq!(
76            deserialized,
77            Pagination {
78                total_elements: None,
79                elements_per_page: None,
80                current_page: None,
81                total_pages: None
82            }
83        );
84    }
85
86    #[test]
87    fn deserialize_bad() {
88        assert!(serde_json::from_value::<Pagination>(json!("xyzabcd")).is_err());
89        assert!(serde_json::from_value::<Pagination>(json!(true)).is_err());
90        assert!(serde_json::from_value::<Pagination>(json!(123)).is_err());
91    }
92}