Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

examples/graphql_issues.rs: Demonstrate variables and paging #481

Merged
merged 1 commit into from
Nov 1, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}
}
}
} "#;
Loading