use async_graphql::Object;
use super::{Connection, UnraisedPage};
use crate::{
Cursor, CursorValue, FieldName, OrderDirection, OrderTerm, TermName,
query::{Edge, Page},
};
const ORDER: &[OrderTerm] = &[OrderTerm::new(
TermName::new("title"),
FieldName::new("title"),
OrderDirection::Asc,
)];
#[derive(Debug, Clone, PartialEq, Eq)]
struct TitleCursor(String);
impl CursorValue for TitleCursor {
fn write_cursor(&self, out: &mut Vec<u8>) {
self.0.write_cursor(out);
}
fn read_cursor(bytes: &[u8]) -> Option<Self> {
String::read_cursor(bytes).map(Self)
}
}
struct RaisedCue {
title: String,
}
#[Object(name = "RaisedCue")]
impl RaisedCue {
async fn title(&self) -> &str {
&self.title
}
}
fn page(titles: &[&str]) -> Page<&'static str, TitleCursor> {
let edges = titles
.iter()
.map(|title| {
Edge::new(
"the projection this page held",
Cursor::at(ORDER, vec![Some(TitleCursor((*title).to_owned()))]),
)
})
.collect::<Vec<_>>();
Page::new(edges, true, false)
}
fn raised(titles: &[&str]) -> Vec<Option<RaisedCue>> {
titles
.iter()
.map(|title| {
Some(RaisedCue {
title: (*title).to_owned(),
})
})
.collect()
}
#[test]
fn the_gathered_nodes_land_on_the_pages_own_cursors() {
let titles = ["alpha", "beta", "delta"];
let Ok(assembled): Result<Connection<RaisedCue, TitleCursor>, _> =
Page::into_connection_of(page(&titles), raised(&titles))
else {
panic!("every slot was filled");
};
assert_eq!(assembled.edges.len(), 3);
assert!(assembled.has_next_page);
assert!(!assembled.has_previous_page);
for (edge, title) in assembled.edges.iter().zip(titles) {
assert_eq!(edge.node.title, title);
assert_eq!(
edge.cursor,
Cursor::at(ORDER, vec![Some(TitleCursor(title.to_owned()))]),
"the cursor is the engine's own, never a re-derivation of it",
);
}
}
#[test]
fn an_empty_page_is_an_empty_connection() {
let Ok(assembled): Result<Connection<RaisedCue, TitleCursor>, _> =
Page::into_connection_of(page(&[]), Vec::new())
else {
panic!("there was nothing to fill");
};
assert!(assembled.edges.is_empty());
}
#[test]
fn an_unfilled_slot_refuses_rather_than_shortening_the_page() {
let titles = ["alpha", "beta", "delta"];
let mut nodes = raised(&titles);
nodes[1] = None;
let Err(refusal) = Page::into_connection_of::<
RaisedCue,
super::DefaultConnectionName,
super::DefaultEdgeName,
>(page(&titles), nodes) else {
panic!("a slot arrived empty and the assembly did not say so");
};
let refusal: UnraisedPage = refusal;
assert_eq!(refusal.missing(), 1);
assert_eq!(refusal.of(), 3);
assert!(refusal.to_string().contains("1 of 3"), "{refusal}");
}
#[test]
fn a_short_list_of_nodes_is_the_same_refusal() {
let titles = ["alpha", "beta", "delta"];
let Err(refusal) = Page::into_connection_of::<
RaisedCue,
super::DefaultConnectionName,
super::DefaultEdgeName,
>(page(&titles), raised(&titles[..2])) else {
panic!("one address never came back and the assembly did not say so");
};
let refusal: UnraisedPage = refusal;
assert_eq!(refusal.missing(), 1);
assert_eq!(refusal.of(), 3);
}