Skip to content

Commit

Permalink
idiomatic result handling
Browse files Browse the repository at this point in the history
  • Loading branch information
pstadler committed Jun 15, 2023
1 parent fbc1467 commit 9cd8a0e
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 59 deletions.
65 changes: 22 additions & 43 deletions src/client.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use core::panic;

use crate::entities;
use crate::persistence;
use reqwest::{
Expand Down Expand Up @@ -32,30 +30,24 @@ impl Client {
let mut headers = HeaderMap::new();
headers.insert(header::ACCEPT, HeaderValue::from_static("application/json"));

let client = match BlockingClient::builder()
let client = BlockingClient::builder()
.cookie_store(true)
.default_headers(headers)
.build()
{
Ok(r) => r,
Err(err) => panic!("Error building client: {}", err),
};
.unwrap();

let session = persistence::Session::load();

Self { client, session }
}

fn preflight(&mut self) -> Result<(), String> {
let res = match self
let res = self
.client
.get("https://finance.yahoo.com")
.header(header::ACCEPT, HeaderValue::from_static("text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8"))
.send()
{
Ok(r) => r,
Err(err) => return Err(format!("Error getting session during preflight: {}", err)),
};
.map_err(|e| format!("Error getting session during preflight: {}", e))?;

let cookies = res
.headers()
Expand All @@ -65,23 +57,19 @@ impl Client {
.collect::<Vec<&str>>()
.join(",");

let res = match self
let res = self
.client
.get("https://query1.finance.yahoo.com/v1/test/getcrumb")
.send()
{
Ok(r) => r,
Err(err) => return Err(format!("Error fetching crumb during preflight: {}", err)),
};
.map_err(|e| format!("Error fetching crumb during preflight: {}", e))?;

let crumb = match res.text() {
Ok(r) => r,
Err(err) => return Err(format!("Error fetching crumb during preflight: {}", err)),
};
let crumb = res
.text()
.map_err(|e| format!("Error fetching crumb during preflight: {}", e))?;

self.session.crumb = crumb;
self.session.cookies = cookies;
self.session.persist().expect("Error persiting session.");
self.session.persist().expect("Error persisting session.");

Ok(())
}
Expand All @@ -103,36 +91,27 @@ impl Client {

pub fn fetch_quotes(&mut self, symbols: &[String]) -> Result<entities::Response, String> {
if self.session.is_empty() {
match self.preflight() {
Ok(_) => (),
Err(err) => return Err(err),
};
self.preflight()?;
}
let mut res: reqwest::blocking::Response = match self._fetch_quotes(symbols) {
Ok(r) => r,
Err(err) => return Err(format!("Error fetching quotes: {}", err)),
};

let mut res: reqwest::blocking::Response = self
._fetch_quotes(symbols)
.map_err(|e| format!("Error fetching quotes: {}", e))?;

if !res.status().is_success() {
if res.status() != reqwest::StatusCode::UNAUTHORIZED {
return Err(format!("Error fetching quotes: {}", res.status()));
}

// acquire new session and retry once if 401
match self.preflight() {
Ok(_) => (),
Err(err) => return Err(err),
};

res = match self._fetch_quotes(symbols) {
Ok(r) => r,
Err(err) => return Err(format!("Error fetching quotes: {}", err)),
};
}
self.preflight()?;

match res.json() {
Ok(r) => Ok(r),
Err(err) => Err(format!("Error parsing response: {}", err)),
res = self
._fetch_quotes(symbols)
.map_err(|e| format!("Error fetching quotes: {}", e))?;
}

res.json()
.map_err(|e| format!("Error parsing response: {}", e))
}
}
18 changes: 9 additions & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,22 @@ fn main() {

let mut client = Client::new();

let res = match client.fetch_quotes(&symbols) {
Ok(r) => r,
Err(err) => {
println!("{}", err);
process::exit(1);
}
};
let res = client
.fetch_quotes(&symbols)
.map_err(|e| {
println!("{}", e);
process::exit(-1)
})
.unwrap();

let colors = get_colors();

for symbol in symbols {
for symbol in symbols.iter() {
let result = res
.quote_response
.result
.iter()
.find(|r| r.symbol == symbol);
.find(|r| &r.symbol == symbol);

if result.is_none() {
println!("No results for symbol \"{}\"", symbol);
Expand Down
14 changes: 7 additions & 7 deletions src/persistence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ impl Session {
}
}

pub fn persist(&mut self) -> Result<(), String> {
match fs::write(&self.path, serde_json::to_string(self).unwrap()) {
Ok(_) => (),
Err(err) => return Err(format!("Error writing temporary file: {}", err)),
}

Ok(())
pub fn persist(&mut self) -> Result<(), std::io::Error> {
fs::write(
&self.path,
serde_json::to_string(self)
.map_err(|e| format!("Error writing temporary file: {}", e))
.unwrap(),
)
}

pub fn is_empty(&self) -> bool {
Expand Down

0 comments on commit 9cd8a0e

Please sign in to comment.