From 561bfd987a354f573a77b8f3df4a52ff300690db Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Fri, 1 Mar 2024 19:01:14 -0800 Subject: [PATCH] Split GithubClient::graphql_query into two methods. This adds a method to add a generic "errors" handler, so callers don't need to worry about errors if they don't need specific ones. This also drops the generic type, since it wasn't really used. --- src/github.rs | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/src/github.rs b/src/github.rs index 012b014d..ff089b88 100644 --- a/src/github.rs +++ b/src/github.rs @@ -2203,11 +2203,17 @@ impl GithubClient { } /// Issues an ad-hoc GraphQL query. - pub async fn graphql_query( + /// + /// You are responsible for checking the `errors` array when calling this + /// function to determine if there is an error. Only use this if you are + /// looking for specific error codes, or don't care about errors. Use + /// [`GithubClient::graphql_query`] if you would prefer to have a generic + /// error message. + pub async fn graphql_query_with_errors( &self, query: &str, vars: serde_json::Value, - ) -> anyhow::Result { + ) -> anyhow::Result { self.json(self.post(&self.graphql_url).json(&serde_json::json!({ "query": query, "variables": vars, @@ -2215,12 +2221,32 @@ impl GithubClient { .await } + /// Issues an ad-hoc GraphQL query. + /// + /// See [`GithubClient::graphql_query_with_errors`] if you need to check + /// for specific errors. + pub async fn graphql_query( + &self, + query: &str, + vars: serde_json::Value, + ) -> anyhow::Result { + let result: serde_json::Value = self.graphql_query_with_errors(query, vars).await?; + if let Some(errors) = result["errors"].as_array() { + let messages: Vec<_> = errors + .iter() + .map(|err| err["message"].as_str().unwrap_or_default()) + .collect(); + anyhow::bail!("error: {}", messages.join("\n")); + } + Ok(result) + } + /// Returns the object ID of the given user. /// /// Returns `None` if the user doesn't exist. pub async fn user_object_id(&self, user: &str) -> anyhow::Result> { let user_info: serde_json::Value = self - .graphql_query( + .graphql_query_with_errors( "query($user:String!) { user(login:$user) { id @@ -2273,7 +2299,7 @@ impl GithubClient { // work on forks. This GraphQL query seems to work fairly reliably, // and seems to cost only 1 point. match self - .graphql_query::( + .graphql_query_with_errors( "query($repository_owner:String!, $repository_name:String!, $user_id:ID!) { repository(owner: $repository_owner, name: $repository_name) { defaultBranchRef {