fmp/
lib.rs

1use reqwest::{Response, StatusCode};
2use serde::de::DeserializeOwned;
3
4pub mod analyst_estimate;
5pub mod company;
6pub mod earning;
7pub mod financial;
8pub mod forex;
9pub mod historical_price;
10pub mod news;
11pub mod period;
12pub mod quote;
13pub mod stock;
14
15pub struct Client {
16    pub base: String,
17    pub api_key: String,
18}
19
20impl Client {
21    pub fn new(endpoint: &str, api_key: &str) -> Self {
22        Client {
23            base: endpoint.to_string(),
24            api_key: api_key.to_string(),
25        }
26    }
27}
28
29async fn decode_content<T>(response: Response) -> Result<T, StatusCode>
30where
31    T: DeserializeOwned,
32{
33    let content = response.json::<T>().await;
34    match content {
35        Ok(s) => Ok(s),
36        Err(e) => {
37            println!("{:?}", e);
38            Err(StatusCode::BAD_REQUEST)
39        }
40    }
41}
42
43async fn request<T>(endpoint: String) -> Result<T, StatusCode>
44where
45    T: DeserializeOwned,
46{
47    let response = reqwest::get(endpoint).await;
48    match response {
49        Ok(r) => {
50            if r.status() != StatusCode::OK {
51                return Err(r.status());
52            }
53            decode_content(r).await
54        }
55        Err(e) => {
56            return if e.is_status() {
57                Err(e.status().unwrap())
58            } else {
59                println!("{:?}", e);
60                Err(StatusCode::BAD_REQUEST)
61            }
62        }
63    }
64}