From 7e4020f2a624016652f214d670ac3f2960fd534c Mon Sep 17 00:00:00 2001 From: Jiahao XU Date: Thu, 30 May 2024 00:04:54 +1000 Subject: [PATCH] Fix unit test for `GhApiClient::get_repo_info` Signed-off-by: Jiahao XU --- .../src/gh_api_client/common.rs | 21 +++++++----------- .../src/gh_api_client/error.rs | 22 +++++++++++++++++-- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/crates/binstalk-git-repo-api/src/gh_api_client/common.rs b/crates/binstalk-git-repo-api/src/gh_api_client/common.rs index 4e2a5e63..b405f2eb 100644 --- a/crates/binstalk-git-repo-api/src/gh_api_client/common.rs +++ b/crates/binstalk-git-repo-api/src/gh_api_client/common.rs @@ -80,12 +80,9 @@ where } #[derive(Deserialize)] -enum GraphQLResponse { - #[serde(rename = "data")] - Data(T), - - #[serde(rename = "errors")] - Errors(GhGraphQLErrors), +struct GraphQLResponse { + data: T, + errors: Option, } #[derive(Serialize)] @@ -131,14 +128,12 @@ where let response = res?.await?; check_http_status_and_header(response.status(), response.headers())?; - let response: GraphQLResponse = response.json().await?; + let mut response: GraphQLResponse = response.json().await?; - match response { - GraphQLResponse::Data(data) => Ok(data), - GraphQLResponse::Errors(errors) if errors.is_rate_limited() => { - Err(GhApiError::RateLimit { retry_after: None }) - } - GraphQLResponse::Errors(errors) => Err(errors.into()), + if let Some(error) = response.errors.take() { + Err(error.into()) + } else { + Ok(response.data) } } } diff --git a/crates/binstalk-git-repo-api/src/gh_api_client/error.rs b/crates/binstalk-git-repo-api/src/gh_api_client/error.rs index 2612a968..1787a372 100644 --- a/crates/binstalk-git-repo-api/src/gh_api_client/error.rs +++ b/crates/binstalk-git-repo-api/src/gh_api_client/error.rs @@ -30,7 +30,7 @@ pub enum GhApiError { Context(Box), #[error("Remote failed to process GraphQL query: {0}")] - GraphQLErrors(#[from] GhGraphQLErrors), + GraphQLErrors(GhGraphQLErrors), #[error("Hit rate-limit, retry after {retry_after:?}")] RateLimit { retry_after: Option }, @@ -58,15 +58,33 @@ impl GhApiError { } } +impl From for GhApiError { + fn from(e: GhGraphQLErrors) -> Self { + if e.is_rate_limited() { + Self::RateLimit { retry_after: None } + } else if e.is_not_found_error() { + Self::NotFound + } else { + Self::GraphQLErrors(e) + } + } +} + #[derive(Debug, Deserialize)] pub struct GhGraphQLErrors(Box<[GraphQLError]>); impl GhGraphQLErrors { - pub(super) fn is_rate_limited(&self) -> bool { + fn is_rate_limited(&self) -> bool { self.0 .iter() .any(|error| matches!(error.error_type, GraphQLErrorType::RateLimited)) } + + fn is_not_found_error(&self) -> bool { + self.0 + .iter() + .any(|error| matches!(&error.error_type, GraphQLErrorType::Other(error_type) if *error_type == "NOT_FOUND")) + } } impl error::Error for GhGraphQLErrors {}