Skip to main content

paginator_rocket/
lib.rs

1use paginator_rs::{
2    Cursor, PaginationParams, PaginatorResponse, PaginatorResponseMeta, SortDirection,
3};
4use rocket::{
5    http::{Header, Status},
6    request::{self, FromRequest, Request},
7    response::{self, Responder},
8    serde::json::Json,
9};
10use serde::Serialize;
11
12#[derive(Debug, Clone)]
13pub struct Pagination {
14    pub params: PaginationParams,
15}
16
17#[rocket::async_trait]
18impl<'r> FromRequest<'r> for Pagination {
19    type Error = &'static str;
20
21    async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
22        let query = req.uri().query();
23
24        let mut page = 1u32;
25        let mut per_page = 20u32;
26        let mut sort_by: Option<String> = None;
27        let mut sort_direction: Option<SortDirection> = None;
28        let mut cursor: Option<Cursor> = None;
29
30        if let Some(query) = query {
31            for (key, value) in query.segments() {
32                match key {
33                    "page" => {
34                        if let Ok(p) = value.parse::<u32>() {
35                            page = p.max(1);
36                        }
37                    }
38                    "per_page" => {
39                        if let Ok(pp) = value.parse::<u32>() {
40                            per_page = pp.clamp(1, 100);
41                        }
42                    }
43                    "sort_by" => {
44                        sort_by = Some(value.to_string());
45                    }
46                    "sort_direction" => {
47                        sort_direction = match value.to_lowercase().as_str() {
48                            "asc" => Some(SortDirection::Asc),
49                            "desc" => Some(SortDirection::Desc),
50                            _ => None,
51                        };
52                    }
53                    "cursor" => match Cursor::decode(value) {
54                        Ok(decoded) => cursor = Some(decoded),
55                        Err(_) => {
56                            return request::Outcome::Error((Status::BadRequest, "invalid cursor"))
57                        }
58                    },
59                    _ => {}
60                }
61            }
62        }
63
64        request::Outcome::Success(Pagination {
65            params: PaginationParams {
66                page,
67                per_page,
68                sort_by,
69                sort_direction,
70                filters: Vec::new(),
71                search: None,
72                disable_total_count: false,
73                cursor,
74            },
75        })
76    }
77}
78
79#[derive(Debug)]
80pub struct PaginatedJson<T> {
81    response: PaginatorResponse<T>,
82}
83
84impl<T> PaginatedJson<T>
85where
86    T: Serialize,
87{
88    pub fn new(data: Vec<T>, params: &PaginationParams, total: u32) -> Self {
89        Self {
90            response: PaginatorResponse {
91                data,
92                meta: PaginatorResponseMeta::new(params.page, params.per_page, total),
93            },
94        }
95    }
96
97    pub fn from_response(response: PaginatorResponse<T>) -> Self {
98        Self { response }
99    }
100}
101
102impl<'r, T> Responder<'r, 'static> for PaginatedJson<T>
103where
104    T: Serialize,
105{
106    fn respond_to(self, req: &'r Request<'_>) -> response::Result<'static> {
107        let json = Json(&self.response);
108        let mut response = json.respond_to(req)?;
109
110        if let Some(total) = self.response.meta.total {
111            response.set_header(Header::new("X-Total-Count", total.to_string()));
112        }
113        if let Some(total_pages) = self.response.meta.total_pages {
114            response.set_header(Header::new("X-Total-Pages", total_pages.to_string()));
115        }
116        response.set_header(Header::new(
117            "X-Current-Page",
118            self.response.meta.page.to_string(),
119        ));
120        response.set_header(Header::new(
121            "X-Per-Page",
122            self.response.meta.per_page.to_string(),
123        ));
124
125        Ok(response)
126    }
127}
128
129pub fn create_paginated_response<T>(
130    data: Vec<T>,
131    params: &PaginationParams,
132    total: u32,
133) -> PaginatedJson<T>
134where
135    T: Serialize,
136{
137    PaginatedJson::new(data, params, total)
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143    use paginator_rs::{CursorDirection, CursorValue};
144    use rocket::local::blocking::Client;
145    use rocket::{get, routes};
146
147    #[get("/users")]
148    fn users(pagination: Pagination) -> String {
149        serde_json::to_string(&pagination.params).unwrap()
150    }
151
152    fn client() -> Client {
153        Client::tracked(rocket::build().mount("/", routes![users])).unwrap()
154    }
155
156    #[test]
157    fn parses_cursor_param() {
158        let cursor = Cursor::new("id".into(), CursorValue::Int(42), CursorDirection::After);
159        let encoded = cursor.encode().unwrap();
160        let client = client();
161        let response = client
162            .get(format!("/users?cursor={encoded}&per_page=5"))
163            .dispatch();
164        assert_eq!(response.status(), Status::Ok);
165        let params: PaginationParams =
166            serde_json::from_str(&response.into_string().unwrap()).unwrap();
167        assert_eq!(params.cursor, Some(cursor));
168        assert_eq!(params.per_page, 5);
169    }
170
171    #[test]
172    fn rejects_invalid_cursor() {
173        let client = client();
174        let response = client.get("/users?cursor=not-a-cursor").dispatch();
175        assert_eq!(response.status(), Status::BadRequest);
176    }
177
178    #[test]
179    fn no_cursor_by_default() {
180        let client = client();
181        let response = client.get("/users?page=2").dispatch();
182        let params: PaginationParams =
183            serde_json::from_str(&response.into_string().unwrap()).unwrap();
184        assert!(params.cursor.is_none());
185        assert_eq!(params.page, 2);
186    }
187}