marketstack/api/
paged.rs

1//! Pagination related types and functions.
2//!
3//! Pagination is done simply for Marketstack, but this allows setting
4//! page limits to have safety guarantees provided by the new-type pattern.
5
6use thiserror::Error;
7
8use crate::api::ApiError;
9
10/// New-type implementation reflecting pagination limits.
11#[derive(Clone, Debug)]
12pub struct PageLimit(pub u16);
13
14impl PageLimit {
15    /// Construct PageLimit type with appropriate checks on valid bounds.
16    pub fn new(limit: u16) -> Result<Self, ApiError<PaginationError>> {
17        if limit <= 1000 {
18            Ok(Self(limit))
19        } else {
20            Err(ApiError::Pagination {
21                source: PaginationError::ExceedLimit,
22            })
23        }
24    }
25}
26
27/// Errors which may occur with pagination.
28#[derive(Debug, Error)]
29#[non_exhaustive]
30pub enum PaginationError {
31    /// Pagination exceeds the limit allowed by Marketstack.
32    #[error("pagination exceeds limit error")]
33    ExceedLimit,
34}
35
36#[cfg(test)]
37mod tests {
38    use super::PageLimit;
39
40    #[test]
41    fn test_new() {
42        let limit = PageLimit::new(5);
43        assert!(limit.is_ok());
44
45        assert_eq!(limit.unwrap().0, 5);
46    }
47
48    #[test]
49    fn test_over_limit() {
50        let limit = PageLimit::new(9999);
51        assert!(limit.is_err());
52
53        let err_message = limit.err().unwrap();
54        assert_eq!(
55            err_message.to_string(),
56            "pagination error: pagination exceeds limit error"
57        );
58    }
59}