Skip to content

Commit

Permalink
Split GithubClient::graphql_query into two methods.
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ehuss committed May 3, 2024
1 parent d5e4458 commit 561bfd9
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions src/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2203,24 +2203,50 @@ impl GithubClient {
}

/// Issues an ad-hoc GraphQL query.
pub async fn graphql_query<T: serde::de::DeserializeOwned>(
///
/// 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<T> {
) -> anyhow::Result<serde_json::Value> {
self.json(self.post(&self.graphql_url).json(&serde_json::json!({
"query": query,
"variables": vars,
})))
.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<serde_json::Value> {
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<Option<String>> {
let user_info: serde_json::Value = self
.graphql_query(
.graphql_query_with_errors(
"query($user:String!) {
user(login:$user) {
id
Expand Down Expand Up @@ -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::<serde_json::Value>(
.graphql_query_with_errors(
"query($repository_owner:String!, $repository_name:String!, $user_id:ID!) {
repository(owner: $repository_owner, name: $repository_name) {
defaultBranchRef {
Expand Down

0 comments on commit 561bfd9

Please sign in to comment.