Skip to content

Commit

Permalink
examples/graphql_issues.rs: Demonstrate variables and paging (#481)
Browse files Browse the repository at this point in the history
  • Loading branch information
Enselic authored Nov 1, 2023
1 parent da0ccab commit 3d4a08c
Showing 1 changed file with 70 additions and 14 deletions.
84 changes: 70 additions & 14 deletions examples/graphql_issues.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,81 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
.personal_token(std::env::var("GITHUB_TOKEN").unwrap())
.build()?;

let query = r#" {
repository(owner:"XAMPPRocky", name:"octocrab") {
issues(last: 2, states: OPEN) {
nodes {
title
url
let mut variables = serde_json::json!({
"owner": "XAMPPRocky",
"name": "octocrab",
"page_size": 5,
});

let pages_to_show = 3;
let mut page = 1;
loop {
if page > pages_to_show {
break;
}

let response: octocrab::Result<serde_json::Value> = octocrab
.graphql(&serde_json::json!({
"query": QUERY,
"variables": variables,
}))
.await;

match response {
Ok(value) => {
println!("Page {page}:");
print_issues(&value);
if !update_page_info(&mut variables, &value) {
break;
}
}
Err(error) => {
println!("{error:#?}");
break;
}
}
} "#;

let response: octocrab::Result<serde_json::Value> = octocrab
.graphql(&serde_json::json!({ "query": query }))
.await;

match response {
Ok(value) => println!("{value:#?}"),
Err(error) => println!("{error:#?}"),
page += 1;
}

Ok(())
}

fn print_issues(value: &serde_json::Value) {
let issues = value["data"]["repository"]["issues"]["nodes"]
.as_array()
.unwrap();

for issue in issues {
println!(
"{} {}",
issue["url"].as_str().unwrap(),
issue["title"].as_str().unwrap()
);
}
}

fn update_page_info(variables: &mut serde_json::Value, value: &serde_json::Value) -> bool {
let page_info = value["data"]["repository"]["issues"]["pageInfo"].clone();
if page_info["hasPreviousPage"].as_bool().unwrap() {
variables["before"] = page_info["startCursor"].clone();
true
} else {
false
}
}

const QUERY: &str = r#" query ($owner: String!, $name: String!, $page_size: Int!, $before: String) {
repository(owner: $owner, name: $name) {
issues(last: $page_size, before: $before, states: OPEN) {
nodes {
title
url
}
pageInfo {
hasPreviousPage
startCursor
}
}
}
} "#;

0 comments on commit 3d4a08c

Please sign in to comment.