Skip to main content

razorpay_api/util/
pagination.rs

1//! Shared list-query parameters and the list-response envelope.
2//!
3//! Every Razorpay list endpoint accepts the same four filters and answers with the
4//! same envelope shape, so both live here once rather than per resource.
5
6use serde::{Deserialize, Serialize};
7
8/// Filters accepted by every `all()` / list endpoint.
9///
10/// All fields are optional and omitted from the query string when [`None`] —
11/// Razorpay rejects `count=null`, so an unset field must not be serialized at all.
12///
13/// # Examples
14///
15/// The common case is "just give me the defaults":
16///
17/// ```
18/// use razorpay_api::ListOptions;
19///
20/// let opts = ListOptions::default();
21/// assert!(opts.count.is_none());
22/// ```
23///
24/// Or build up a filtered window with the chainable setters:
25///
26/// ```
27/// use razorpay_api::ListOptions;
28///
29/// let opts = ListOptions::new().count(25).skip(50).from(1_700_000_000);
30/// assert_eq!(opts.count, Some(25));
31/// assert_eq!(opts.skip, Some(50));
32/// ```
33#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
34pub struct ListOptions {
35    /// Unix timestamp (seconds); returns records created at or after this time.
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub from: Option<i64>,
38
39    /// Unix timestamp (seconds); returns records created at or before this time.
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub to: Option<i64>,
42
43    /// Number of records to fetch. Razorpay's default is 10 and its maximum is 100.
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub count: Option<u32>,
46
47    /// Number of records to skip — combine with [`count`](Self::count) to page.
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub skip: Option<u32>,
50}
51
52impl ListOptions {
53    /// An empty set of filters, equivalent to [`ListOptions::default()`].
54    pub fn new() -> Self {
55        Self::default()
56    }
57
58    /// Only return records created at or after this Unix timestamp (seconds).
59    pub fn from(mut self, from: i64) -> Self {
60        self.from = Some(from);
61        self
62    }
63
64    /// Only return records created at or before this Unix timestamp (seconds).
65    pub fn to(mut self, to: i64) -> Self {
66        self.to = Some(to);
67        self
68    }
69
70    /// Fetch at most `count` records. Razorpay caps this at 100.
71    pub fn count(mut self, count: u32) -> Self {
72        self.count = Some(count);
73        self
74    }
75
76    /// Skip the first `skip` records.
77    pub fn skip(mut self, skip: u32) -> Self {
78        self.skip = Some(skip);
79        self
80    }
81}
82
83/// The envelope every list endpoint returns: `{"entity": "collection", "count": N, "items": [...]}`.
84///
85/// Generic over the item type so one struct serves every resource.
86///
87/// # Examples
88///
89/// ```
90/// # use razorpay_api::Collection;
91/// # use razorpay_api::resources::Order;
92/// # fn demo(page: Collection<Order>) {
93/// for order in &page {
94///     println!("{} is {:?}", order.id, order.status);
95/// }
96/// # }
97/// ```
98#[derive(Debug, Clone, PartialEq, Deserialize)]
99pub struct Collection<T> {
100    /// Always `"collection"` for list responses.
101    #[serde(default)]
102    pub entity: String,
103
104    /// Number of items in [`items`](Self::items) — not the total matching records.
105    #[serde(default)]
106    pub count: u32,
107
108    /// The page of records.
109    #[serde(default = "Vec::new")]
110    pub items: Vec<T>,
111}
112
113impl<T> Collection<T> {
114    /// Number of items in this page.
115    pub fn len(&self) -> usize {
116        self.items.len()
117    }
118
119    /// Whether this page came back empty.
120    pub fn is_empty(&self) -> bool {
121        self.items.is_empty()
122    }
123
124    /// Borrowing iterator over the page's items.
125    pub fn iter(&self) -> std::slice::Iter<'_, T> {
126        self.items.iter()
127    }
128}
129
130impl<T> IntoIterator for Collection<T> {
131    type Item = T;
132    type IntoIter = std::vec::IntoIter<T>;
133
134    fn into_iter(self) -> Self::IntoIter {
135        self.items.into_iter()
136    }
137}
138
139impl<'a, T> IntoIterator for &'a Collection<T> {
140    type Item = &'a T;
141    type IntoIter = std::slice::Iter<'a, T>;
142
143    fn into_iter(self) -> Self::IntoIter {
144        self.items.iter()
145    }
146}
147
148impl<T> Default for Collection<T> {
149    fn default() -> Self {
150        Self {
151            entity: "collection".to_string(),
152            count: 0,
153            items: Vec::new(),
154        }
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    #[test]
163    fn none_fields_are_omitted_entirely() {
164        // `count=null` in a query string is a 400 from Razorpay, so absence matters.
165        let qs = serde_urlencoded::to_string(ListOptions::default()).unwrap();
166        assert_eq!(qs, "");
167    }
168
169    #[test]
170    fn set_fields_serialize() {
171        let qs = serde_urlencoded::to_string(ListOptions::new().count(10).skip(20)).unwrap();
172        assert_eq!(qs, "count=10&skip=20");
173    }
174
175    #[test]
176    fn collection_deserializes_and_iterates() {
177        let json = r#"{"entity":"collection","count":2,"items":[1,2]}"#;
178        let c: Collection<i64> = serde_json::from_str(json).unwrap();
179        assert_eq!(c.count, 2);
180        assert_eq!(c.len(), 2);
181        assert!(!c.is_empty());
182        assert_eq!(c.iter().sum::<i64>(), 3);
183        assert_eq!(c.into_iter().collect::<Vec<_>>(), vec![1, 2]);
184    }
185
186    #[test]
187    fn missing_items_defaults_to_empty_rather_than_failing() {
188        let c: Collection<i64> = serde_json::from_str(r#"{"entity":"collection","count":0}"#).unwrap();
189        assert!(c.is_empty());
190    }
191}