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
102
103
104
105
106
107
108
109
110
111
112
113
use super::{Cursor, Request};
#[derive(PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Response<R, D>
where
R: Request,
D: serde::de::DeserializeOwned + PartialEq, {
pub data: D,
pub pagination: Option<Cursor>,
pub request: Option<R>,
pub total: Option<i64>,
pub other: Option<serde_json::Map<String, serde_json::Value>>,
}
impl<R, D> Response<R, D>
where
R: Request,
D: serde::de::DeserializeOwned + PartialEq,
{
pub fn get_other<Q, V>(&self, key: &Q) -> Result<Option<V>, serde_json::Error>
where
String: std::borrow::Borrow<Q>,
Q: ?Sized + Ord + Eq + std::hash::Hash,
V: serde::de::DeserializeOwned, {
use std::borrow::Borrow as _;
match &key {
total if &String::from("total").borrow() == total => {
if let Some(total) = self.total {
let total = serde_json::json!(total);
Some(serde_json::from_value(total)).transpose()
} else {
Ok(None)
}
}
_ => self
.other
.as_ref()
.and_then(|map| map.get(key.borrow()))
.map(|v| serde_json::from_value(v.clone()))
.transpose(),
}
}
}
impl<R, D, T> Response<R, D>
where
R: Request,
D: IntoIterator<Item = T> + PartialEq + serde::de::DeserializeOwned,
{
pub fn first(self) -> Option<T> { self.data.into_iter().next() }
}
#[cfg(feature = "client")]
impl<R, D> Response<R, D>
where
R: Request<Response = D> + Clone + super::Paginated + super::RequestGet + std::fmt::Debug,
D: serde::de::DeserializeOwned + std::fmt::Debug + PartialEq,
{
pub async fn get_next<'a, C: crate::HttpClient<'a>>(
self,
client: &'a super::HelixClient<'a, C>,
token: &(impl super::TwitchToken + ?Sized),
) -> Result<
Option<Response<R, D>>,
super::ClientRequestError<<C as crate::HttpClient<'a>>::Error>,
> {
if let Some(mut req) = self.request.clone() {
if self.pagination.is_some() {
req.set_pagination(self.pagination);
let res = client.req_get(req, token).await.map(Some);
if let Ok(Some(r)) = res {
if r.data == self.data {
Ok(None)
} else {
Ok(Some(r))
}
} else {
res
}
} else {
Ok(None)
}
} else {
Err(super::ClientRequestError::Custom(
"no source request attached".into(),
))
}
}
}