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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
use std::fmt::Debug;
use async_stream::try_stream;
use futures::pin_mut;
use futures::stream::{Stream, TryStreamExt};
use reqwest::RequestBuilder;
use serde::de::DeserializeOwned;
use serde::Serialize;
use super::request;
use super::Error;
pub trait Resource {
type Id: Debug + Serialize;
type Root: DeserializeOwned;
fn resource_id(&self) -> Self::Id;
}
#[derive(Serialize)]
struct Query<T: Serialize> {
#[serde(skip_serializing_if = "Option::is_none")]
limit: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
marker: Option<T>,
}
fn chunks<T>(
builder: RequestBuilder,
limit: Option<usize>,
starting_with: Option<T::Id>,
) -> impl Stream<Item = Result<Vec<T>, Error>>
where
T: Resource + Unpin,
T::Root: Into<Vec<T>> + Send,
{
let mut marker = starting_with;
try_stream! {
loop {
let prepared = builder
.try_clone()
.expect("Builder with a streaming body cannot be used")
.query(&Query{ limit: limit, marker: marker.take() });
let result: T::Root = request::fetch_json(prepared).await?;
let items = result.into();
if let Some(new_m) = items.last() {
marker = Some(new_m.resource_id());
yield items;
} else {
break
}
}
}
}
pub fn paginated<T>(
builder: RequestBuilder,
limit: Option<usize>,
starting_with: Option<T::Id>,
) -> impl Stream<Item = Result<T, Error>>
where
T: Resource + Unpin,
T::Root: Into<Vec<T>> + Send,
{
try_stream! {
let iter = chunks(builder, limit, starting_with);
pin_mut!(iter);
while let Some(chunk) = iter.try_next().await? {
for item in chunk {
yield item;
}
}
}
}