use juniper::GraphQLObject;
use crate::{cursor_from_encoded_string, Cursor};
use crate::cursor_errors::CursorError;
#[derive(Debug, GraphQLObject, Eq, PartialEq, Clone)]
#[graphql(description = "Pagination information")]
pub struct PageInfo {
#[graphql(description = "Indicates whether there is a page following this current one")]
pub has_next_page: bool,
#[graphql(description = "Indicates whether there is a page preceding this one")]
pub has_prev_page: bool,
#[graphql(description = "An opaque cursor that when passed to after: in a query will return the previous page of results.")]
pub start_cursor: Option<String>,
#[graphql(description = "An opaque cursor that when passed to after: in a query will return the following page of results.")]
pub end_cursor: Option<String>,
}
#[derive(Debug, GraphQLObject, Eq, PartialEq, Clone)]
#[graphql(description = "Page request")]
pub struct PageRequest {
#[graphql(description = "The number of items to return.")]
pub first: Option<i32>,
#[graphql(description = "A cursor to use as the pointer to the start of the page.")]
pub after: Option<String>,
}
impl PageRequest {
pub fn new(first: Option<i32>, after: Option<impl Cursor>) -> Self {
PageRequest {
first,
after: after.map(|after| after.to_encoded_string())
}
}
pub fn parsed_cursor<T>(&self) -> Result<Option<T>, CursorError> where T: Cursor<CursorType = T> {
if self.after.is_none() {
return Ok(None);
}
let decoded_cursor = cursor_from_encoded_string(self.after.as_ref().unwrap())?;
Ok(Some(decoded_cursor))
}
}
#[cfg(test)]
mod tests {
use crate::{OffsetCursor, PageRequest, StringCursor};
#[test]
fn test_new() {
let pr = PageRequest::new(Some(10), Some(StringCursor::new("some-string-cursor".to_string())));
assert_eq!(pr.first, Some(10));
assert_eq!(pr.after, Some("c3RyaW5nOnNvbWUtc3RyaW5nLWN1cnNvcg==".to_string()));
}
#[test]
fn test_decoding_cursor_from_page_request() {
let request = PageRequest { first: Some(10), after: Some("b2Zmc2V0OjE6MTA=".to_string()) };
let decoded_cursor = request.parsed_cursor::<OffsetCursor>().unwrap();
assert_eq!(decoded_cursor.unwrap().offset, 1);
}
}