added more graceful err handling of file_not_found +progress_bar

This commit is contained in:
Steven 2023-07-28 22:07:36 -04:00
parent cffa3f5a04
commit 0d7f2380da
3 changed files with 174 additions and 20 deletions

View file

@ -1,7 +1,8 @@
use reqwest::Error;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, env, fs::File, fs::OpenOptions, io::BufReader};
use tokio::time::Duration;
use indicatif::{ProgressBar, ProgressStyle};
/// A struct to represent a Card returned from the API.
#[derive(Serialize, Deserialize, Debug, Clone)]
@ -37,7 +38,7 @@ struct CardFile {
///
/// Note: There is a delay of 100ms between each API request as per the API rules.
#[tokio::main]
async fn main() -> Result<(), Error> {
async fn main() -> Result<(), Box<std::io::Error>> {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
eprintln!("Please provide the path to the JSON file as an argument.");
@ -45,17 +46,39 @@ async fn main() -> Result<(), Error> {
}
let file_path = &args[1];
let file = File::open(file_path).unwrap();
let file = match File::open(file_path) {
Ok(file) => file,
Err(error) => {
eprintln!("There was a problem opening the file: {:?}", error);
return Err(Box::new(std::io::Error::new(
std::io::ErrorKind::NotFound,
"File not found",
)));
}
};
let reader = BufReader::new(file);
let mut cards_data: CardFile = serde_json::from_reader(reader).unwrap();
let pb = ProgressBar::new(cards_data.cards.len() as u64);
let style = ProgressStyle::default_bar()
.template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} ({eta})")
.unwrap();
let style = style.progress_chars("#>-");
pb.set_style(style);
for card_from_file in &mut cards_data.cards {
let request_url = format!(
"https://api.scryfall.com/cards/named?exact={}",
card_from_file.name
);
let response = reqwest::get(&request_url).await?;
let card: Card = response.json().await?;
let response = reqwest::get(&request_url).await
.map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err.to_string()))?;
let card: Card = response.json().await
.map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err.to_string()))?;
if let Some(price) = card.prices.get("usd") {
if let Some(price_str) = price {
@ -65,9 +88,12 @@ async fn main() -> Result<(), Error> {
}
}
pb.inc(1);
tokio::time::sleep(Duration::from_millis(100)).await;
}
pb.finish_with_message("Completed!");
let file = OpenOptions::new()
.write(true)
.truncate(true)
@ -78,3 +104,4 @@ async fn main() -> Result<(), Error> {
Ok(())
}