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
use {
    serde::Deserialize,
    std::convert::AsRef,
};

#[derive(Debug, Deserialize)]
#[allow(non_snake_case)]
pub struct PageInfo {
    pub startCursor: Option<String>,
    pub endCursor: Option<String>,
    pub hasPreviousPage: Option<bool>,
    pub hasNextPage: Option<bool>,
}

#[derive(Debug, Deserialize)]
#[allow(non_snake_case)]
pub struct List<Item> {
    pub totalCount: Option<usize>,
    pub nodes: Vec<Item>,
    pub pageInfo: Option<PageInfo>,
}

impl<Item> List<Item> {
    pub fn query_page_selector<S: AsRef<str>>(
        after: &Option<S>,
        first: usize,        // page max size
        other_clauses: &str, // filters & ordering clauses
    ) -> String {
        if let Some(cursor) = after.as_ref() {
            format!(
                r#"(first:{} after:"{}" {})"#,
                first,
                cursor.as_ref(),
                other_clauses
            )
        } else {
            format!(r#"(first:{} {})"#, first, other_clauses)
        }
    }
    pub fn query_page_body(item_query_part: &str) -> String {
        format!(
            r#"{{
            totalCount
            nodes {}
            pageInfo {{
                startCursor
                endCursor
                hasPreviousPage
                hasNextPage
            }}
        }}"#,
            item_query_part
        )
    }
    pub fn next_page_cursor(self) -> Option<String> {
        if let Some(page_info) = self.pageInfo {
            if page_info.hasNextPage == Some(true) {
                return page_info.endCursor;
            }
        }
        None
    }
}

/// a structure matching `{ totalCount}`, convenient
/// when you want the number of items in a collections
#[derive(Debug, Deserialize, Clone, Copy)]
#[allow(non_snake_case)]
pub struct Count {
    pub totalCount: usize,
}
impl From<Count> for usize {
    fn from(count: Count) -> usize {
        count.totalCount
    }
}
impl Count {
    /// build the query part for the count of something.
    ///
    /// Can be used for a whole query or just a property.
    /// Example:
    /// ```
    /// use byo_graphql::*;
    /// assert_eq!(
    ///     Count::query("repositories", "isFork: false"),
    ///     r#"repositories(isFork: false){ totalCount }"#,
    /// );
    /// ```
    pub fn query(
        collection_name: &str,
        filter: &str,
    ) -> String {
        format!(r#"{}({}){{ totalCount }}"#, collection_name, filter)
    }
}