1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//! Pagination types for API responses.
use serde::{Deserialize, Serialize};
/// A paginated response using page numbers.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaginatedResponse<T> {
/// Total count of items.
pub count: Option<i64>,
/// URL for the next page.
pub next: Option<String>,
/// URL for the previous page.
pub previous: Option<String>,
/// The results for this page.
pub results: Vec<T>,
}
impl<T> PaginatedResponse<T> {
/// Returns true if there is a next page.
pub fn has_next(&self) -> bool {
self.next.is_some()
}
/// Returns true if there is a previous page.
pub fn has_previous(&self) -> bool {
self.previous.is_some()
}
/// Returns the total number of pages (if count is available).
///
/// Returns `None` if `page_size` is zero or the reported count is negative.
pub fn total_pages(&self, page_size: usize) -> Option<usize> {
if page_size == 0 {
return None;
}
self.count
.filter(|c| *c >= 0)
.map(|c| (c as usize).div_ceil(page_size))
}
}
/// A cursor-based paginated response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CursorPaginatedResponse<T> {
/// Cursor for the next page.
pub next: Option<String>,
/// Cursor for the previous page.
pub previous: Option<String>,
/// The results for this page.
pub results: Vec<T>,
}
impl<T> CursorPaginatedResponse<T> {
/// Returns true if there is a next page.
pub fn has_next(&self) -> bool {
self.next.is_some()
}
/// Returns true if there is a previous page.
pub fn has_previous(&self) -> bool {
self.previous.is_some()
}
/// Extracts the cursor value from the next URL.
pub fn next_cursor(&self) -> Option<String> {
self.next.as_ref().and_then(|url| {
url::Url::parse(url).ok().and_then(|u| {
u.query_pairs()
.find(|(k, _)| k == "cursor")
.map(|(_, v)| v.to_string())
})
})
}
/// Extracts the page number from the next URL.
pub fn next_page(&self) -> Option<i32> {
self.next.as_ref().and_then(|url| {
url::Url::parse(url).ok().and_then(|u| {
u.query_pairs()
.find(|(k, _)| k == "page")
.and_then(|(_, v)| v.parse().ok())
})
})
}
}