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
//! proxer api library
extern crate chrono;
#[macro_use]
extern crate hyper;
#[macro_use]
extern crate log;
extern crate reqwest;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate serde_urlencoded;

pub mod error;
pub mod response;
pub mod api;
pub mod prelude;
pub mod client;
pub mod tests;

pub use client::Client;
pub use error::Error;
pub use prelude::*;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::fmt;

/// Every struct that is an endpoint, implements this trait.
pub trait Endpoint: Serialize {
	type ResponseType: std::fmt::Debug + Clone + DeserializeOwned;
	const URL: &'static str;
}

pub trait PageableEndpoint
where
	Self: Endpoint + std::marker::Sized,
	<Self as Endpoint>::ResponseType: IntoIterator + Clone,
	<<Self as Endpoint>::ResponseType as std::iter::IntoIterator>::Item: Clone + fmt::Debug,
{
	fn pager(self, client: Client) -> Pager<Self>;

	fn page_mut(&mut self) -> &mut Option<usize>;
	fn limit_mut(&mut self) -> &mut Option<usize>;
}

#[derive(Clone, Debug)]
pub struct Pager<T>
where
	T: Endpoint,
	<T as Endpoint>::ResponseType: IntoIterator + Clone + std::fmt::Debug,
	<<T as Endpoint>::ResponseType as std::iter::IntoIterator>::Item: Clone + fmt::Debug,
{
	client: Client,
	shifted: usize,
	endpoint: T,
	data: Vec<<<T as Endpoint>::ResponseType as IntoIterator>::Item>,
}

impl<T> Pager<T>
where
	T: Endpoint + PageableEndpoint,
	T: Clone + fmt::Debug,
	<T as Endpoint>::ResponseType: IntoIterator + Clone + fmt::Debug,
	<<T as Endpoint>::ResponseType as std::iter::IntoIterator>::Item: Clone + fmt::Debug,
{
	pub fn new(
		client: Client,
		mut endpoint: T,
		start: Option<usize>,
		limit: Option<usize>,
	) -> Self {
		match (endpoint.page_mut(), start) {
			(&mut None, None) => *endpoint.page_mut() = Some(0),
			(&mut None, Some(_)) => *endpoint.page_mut() = start,
			_ => {}
		}

		match (endpoint.limit_mut(), limit) {
			(&mut None, None) => *endpoint.limit_mut() = Some(750),
			(&mut None, Some(_)) => *endpoint.limit_mut() = limit,
			_ => {}
		}

		debug!(
			"initialize new pager: page: {}, limit {}",
			endpoint.page_mut().unwrap(),
			endpoint.limit_mut().unwrap(),
		);

		Self {
			client: client,
			data: Vec::new(),
			shifted: 0,
			endpoint: endpoint,
		}
	}

	fn page_mut(&mut self) -> usize {
		self.endpoint.page_mut().unwrap()
	}

	fn limit_mut(&mut self) -> usize {
		self.endpoint.limit_mut().unwrap()
	}

	fn next_page(&mut self) {
		*self.endpoint.page_mut() = Some(self.page_mut() + 1);
	}
}

impl<T> Iterator for Pager<T>
where
	T: Endpoint,
	T: PageableEndpoint + Clone + std::fmt::Debug,
	<T as Endpoint>::ResponseType: IntoIterator,
	<<T as Endpoint>::ResponseType as std::iter::IntoIterator>::Item: Clone + fmt::Debug,
{
	type Item = Result<<<T as Endpoint>::ResponseType as IntoIterator>::Item, error::Error>;

	fn next(&mut self) -> Option<Self::Item> {
		match self.data.pop() {
			Some(i) => {
				debug!("returning from buffer");
				self.shifted += 1;

				debug!(
					"buffer: remaining/shifted: {}/{}",
					self.data.len(),
					self.shifted,
				);
				Some(Ok(i))
			}
			None => {
				debug!("expected shifted: {}", self.page_mut() * self.limit_mut());
				debug!("actually shifted: {}", self.shifted);

				if self.page_mut() * self.limit_mut() > self.shifted {
					debug!("reached the last page");
					return None;
				}

				debug!("fetching new data");
				let res = self.client.execute(self.endpoint.clone());

				self.next_page();

				match res {
					Ok(res) => {
						for var in res.into_iter() {
							self.data.push(var);
						}
						debug!("filled buffer with {} entries", self.data.len());

						self.next()
					}
					Err(e) => Some(Err(e)),
				}
			}
		}
	}
}