From 3f91a005a1924e17b95ebdd13b9064bdffb79e6a Mon Sep 17 00:00:00 2001 From: jecaro Date: Mon, 23 Sep 2024 14:13:03 +0200 Subject: [PATCH] Refactor some requests that might return no field --- src/lms/mod.rs | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/src/lms/mod.rs b/src/lms/mod.rs index a990435..a65de55 100644 --- a/src/lms/mod.rs +++ b/src/lms/mod.rs @@ -171,12 +171,7 @@ impl LmsClient { (|| async { let (request, field) = LmsRequest::artist(name); let lms_response = self.post(&request).await?; - as_string(lms_response, &field).map(Some).or_else(|e| { - match e.downcast_ref::() { - Some(ResultError::NoField { .. }) => Ok(None), - _ => Err(e), - } - }) + as_string_or_not_there(lms_response, &field) })() .await, anyhow!("Error get_artist"), @@ -190,12 +185,7 @@ impl LmsClient { (|| async { let (request, field) = LmsRequest::current_title(name); let lms_response = self.post(&request).await?; - as_string(lms_response, &field).map(Some).or_else(|e| { - match e.downcast_ref::() { - Some(ResultError::NoField { .. }) => Ok(None), - _ => Err(e), - } - }) + as_string_or_not_there(lms_response, &field) })() .await, anyhow!("Error get_current_title"), @@ -209,12 +199,7 @@ impl LmsClient { (|| async { let (request, field) = LmsRequest::album(name); let lms_response = self.post(&request).await?; - as_string(lms_response, &field).map(Some).or_else(|e| { - match e.downcast_ref::() { - Some(ResultError::NoField { .. }) => Ok(None), - _ => Err(e), - } - }) + as_string_or_not_there(lms_response, &field) })() .await, anyhow!("Error get_album"), @@ -349,6 +334,15 @@ fn as_string(response: LmsResponse, field: &String) -> Result { } } +fn as_string_or_not_there(response: LmsResponse, field: &String) -> Result> { + as_string(response, &field) + .map(Some) + .or_else(|e| match e.downcast_ref::() { + Some(ResultError::NoField { .. }) => Ok(None), + _ => Err(e), + }) +} + fn as_mode(response: LmsResponse, field: &String) -> Result { let value = result_field(response, &field)?; match value {