Skip to content

Commit

Permalink
Make encode_image_from_url to return error for invalid input
Browse files Browse the repository at this point in the history
  • Loading branch information
marshallku committed Apr 26, 2024
1 parent 5ed9bcb commit 4c2d2fb
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
16 changes: 8 additions & 8 deletions src/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,28 @@ use crate::url::is_valid_url;

pub async fn encode_image_from_url(url: &str) -> Result<String, String> {
if !is_valid_url(url) {
return Ok("".to_string());
return Err("Invalid URL".to_string());
}

let response = match get(url).await {
Ok(response) => response,
Err(e) => {
error!("Error fetching image: {:?}", e);
return Ok("".to_string());
return Err("Failed to fetch image".to_string());
}
};
let bytes = match response.bytes().await {
Ok(bytes) => bytes,
Err(e) => {
error!("Error reading image: {:?}", e);
return Ok("".to_string());
return Err("Failed to read image".to_string());
}
};
let mime = from_path(url).first_or_octet_stream();

if mime.type_() != "image" {
error!("Invalid mime type: {:?}", mime.type_());
return Ok("".to_string());
return Err("Invalid mime type".to_string());
}

let encoded = general_purpose::STANDARD_NO_PAD.encode(&bytes);
Expand Down Expand Up @@ -59,16 +59,16 @@ mod tests {
#[tokio::test]
async fn test_encode_image_from_url_invalid_url() {
let url = "https://www/";
let result = encode_image_from_url(url).await.unwrap();
let result = encode_image_from_url(url).await;

assert_eq!(result, "");
assert!(result.is_err());
}

#[tokio::test]
async fn test_encode_image_from_url_not_image() {
let url = "https://www.google.com";
let result = encode_image_from_url(url).await.unwrap();
let result = encode_image_from_url(url).await;

assert_eq!(result, "");
assert!(result.is_err());
}
}
9 changes: 8 additions & 1 deletion src/fetcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,14 @@ pub async fn fetch_random_food() -> Result<MealData, Error> {
return Ok(get_default_meal());
}
};
let encoded_thumbnail = encode_image_from_url(&meal.meal_thumbnail).await.unwrap();

let encoded_thumbnail = match encode_image_from_url(&meal.meal_thumbnail).await {
Ok(encoded_thumbnail) => encoded_thumbnail,
Err(e) => {
error!("Error encoding image: {:?}", e);
return Ok(get_default_meal());
}
};

meal.meal_thumbnail = encoded_thumbnail;

Expand Down

0 comments on commit 4c2d2fb

Please sign in to comment.