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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
use std::collections::HashMap;
use serde::de::DeserializeOwned;
use serde_derive::{Deserialize, Serialize};
use crate::config::{err, ok, Client, Response};
use crate::error::StripeError;
use crate::resources::ApiVersion;
#[derive(Clone, Default)]
pub struct AppInfo {
pub name: String,
pub url: Option<String>,
pub version: Option<String>,
}
#[derive(Clone, Default)]
pub struct Headers {
pub client_id: Option<String>,
pub stripe_version: Option<ApiVersion>,
pub stripe_account: Option<String>,
pub user_agent: Option<String>,
}
pub trait Object {
type Id;
fn id(&self) -> Self::Id;
fn object(&self) -> &'static str;
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Deleted<T> {
pub id: T,
pub deleted: bool,
}
#[doc(hidden)]
#[derive(Serialize)]
pub struct Expand<'a> {
#[serde(skip_serializing_if = "Expand::is_empty")]
pub expand: &'a [&'a str],
}
impl Expand<'_> {
pub(crate) fn is_empty(expand: &[&str]) -> bool {
expand.is_empty()
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Expandable<T: Object> {
Id(T::Id),
Object(Box<T>),
}
impl<T> Expandable<T>
where
T: Object,
T::Id: Clone,
{
pub fn id(&self) -> T::Id {
match self {
Expandable::Id(id) => id.clone(),
Expandable::Object(obj) => obj.id(),
}
}
}
impl<T: Object> Expandable<T> {
pub fn is_object(&self) -> bool {
match self {
Expandable::Id(_) => false,
Expandable::Object(_) => true,
}
}
pub fn as_object(&self) -> Option<&T> {
match self {
Expandable::Id(_) => None,
Expandable::Object(obj) => Some(&obj),
}
}
#[deprecated(
note = "Renamed `into_object` per rust api design guidelines (may be removed in v0.12)"
)]
#[allow(clippy::wrong_self_convention)]
pub fn to_object(self) -> Option<T> {
match self {
Expandable::Id(_) => None,
Expandable::Object(obj) => Some(*obj),
}
}
pub fn into_object(self) -> Option<T> {
match self {
Expandable::Id(_) => None,
Expandable::Object(obj) => Some(*obj),
}
}
}
pub trait Paginate {
type Cursor: AsCursor;
fn cursor(&self) -> Self::Cursor;
}
pub trait AsCursor: AsRef<str> {}
impl<'a> AsCursor for &'a str {}
impl AsCursor for String {}
impl<T> Paginate for T
where
T: Object,
T::Id: AsCursor,
{
type Cursor = T::Id;
fn cursor(&self) -> Self::Cursor {
self.id()
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct List<T> {
pub data: Vec<T>,
pub has_more: bool,
pub total_count: Option<u64>,
pub url: String,
}
impl<T> Default for List<T> {
fn default() -> Self {
List { data: Vec::new(), has_more: false, total_count: None, url: String::new() }
}
}
impl<T: Clone> Clone for List<T> {
fn clone(&self) -> Self {
List {
data: self.data.clone(),
has_more: self.has_more,
total_count: self.total_count,
url: self.url.clone(),
}
}
}
impl<T: DeserializeOwned + Send + 'static> List<T> {
pub fn get_next(client: &Client, url: &str, last_id: &str) -> Response<List<T>> {
if url.starts_with("/v1/") {
let mut url = url.trim_start_matches("/v1/").to_string();
if url.contains('?') {
url.push_str(&format!("&starting_after={}", last_id));
} else {
url.push_str(&format!("?starting_after={}", last_id));
}
client.get(&url)
} else {
err(StripeError::UnsupportedVersion)
}
}
}
impl<T: Paginate + DeserializeOwned + Send + 'static> List<T> {
#[cfg(feature = "blocking")]
pub fn get_all(self, client: &Client) -> Response<Vec<T>> {
let mut data = Vec::new();
let mut next = self;
loop {
if next.has_more {
let resp = next.next(&client)?;
data.extend(next.data);
next = resp;
} else {
data.extend(next.data);
break;
}
}
Ok(data)
}
pub fn next(&self, client: &Client) -> Response<List<T>> {
if let Some(last_id) = self.data.last().map(|d| d.cursor()) {
List::get_next(client, &self.url, last_id.as_ref())
} else {
ok(List {
data: Vec::new(),
has_more: false,
total_count: self.total_count,
url: self.url.clone(),
})
}
}
}
pub type Metadata = HashMap<String, String>;
pub type Timestamp = i64;
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub struct RangeBounds<T> {
pub gt: Option<T>,
pub gte: Option<T>,
pub lt: Option<T>,
pub lte: Option<T>,
}
impl<T> Default for RangeBounds<T> {
fn default() -> Self {
RangeBounds { gt: None, gte: None, lt: None, lte: None }
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum RangeQuery<T> {
Exact(T),
Bounds(RangeBounds<T>),
}
impl<T> RangeQuery<T> {
pub fn eq(value: T) -> RangeQuery<T> {
RangeQuery::Exact(value)
}
pub fn gt(value: T) -> RangeQuery<T> {
RangeQuery::Bounds(RangeBounds { gt: Some(value), ..Default::default() })
}
pub fn gte(value: T) -> RangeQuery<T> {
RangeQuery::Bounds(RangeBounds { gte: Some(value), ..Default::default() })
}
pub fn lt(value: T) -> RangeQuery<T> {
RangeQuery::Bounds(RangeBounds { lt: Some(value), ..Default::default() })
}
pub fn lte(value: T) -> RangeQuery<T> {
RangeQuery::Bounds(RangeBounds { lte: Some(value), ..Default::default() })
}
}
#[derive(Clone, Debug, Serialize)]
#[serde(untagged)]
pub enum IdOrCreate<'a, T> {
Id(&'a str),
Create(&'a T),
}
pub fn to_snakecase(camel: &str) -> String {
let mut i = 0;
let mut snake = String::new();
let mut chars = camel.chars().peekable();
while let Some(ch) = chars.next() {
if ch.is_uppercase() {
if i > 0 && !chars.peek().unwrap_or(&'A').is_uppercase() {
snake.push('_');
}
snake.push(ch.to_lowercase().next().unwrap_or(ch));
} else {
snake.push(ch);
}
i += 1;
}
snake
}
#[cfg(test)]
mod tests {
#[test]
fn to_snakecase() {
use super::to_snakecase;
assert_eq!(to_snakecase("snake_case").as_str(), "snake_case");
assert_eq!(to_snakecase("CamelCase").as_str(), "camel_case");
assert_eq!(to_snakecase("XMLHttpRequest").as_str(), "xml_http_request");
assert_eq!(to_snakecase("UPPER").as_str(), "upper");
assert_eq!(to_snakecase("lower").as_str(), "lower");
}
}