newsdata_io_api/newsdata_io/
requests.rs1use std::collections::HashMap;
2
3use super::NewsdataIO;
4use crate::Error;
5use crate::{ApiResult, Json};
6
7use log::{debug, error};
8
9pub trait Requests {
10 fn get(&self, sub_url: &str, query_params: Option<HashMap<String, String>>) -> ApiResult<Json>;
11}
12
13impl Requests for NewsdataIO {
14 fn get(&self, sub_url: &str, query_params: Option<HashMap<String, String>>) -> ApiResult<Json> {
15 let mut request = self
16 .agent
17 .get(&(format!("https://newsdata.io/api/1/{}", sub_url)))
18 .query("apikey", self.auth.get_api_key().as_str());
19 match query_params {
20 Some(params) => {
21 for (key, value) in params {
22 request = request.query(key.as_str(), value.as_str());
23 }
24 }
25 None => {}
26 };
27 let response = request.set("Content-Type", "application/json").call();
28 deal_response(response, sub_url)
29 }
30}
31
32fn deal_response(response: Result<ureq::Response, ureq::Error>, sub_url: &str) -> ApiResult<Json> {
33 match response {
34 Ok(response) => {
35 let json = response.into_json::<Json>().unwrap();
36 debug!("<== ✔️\n\tDone api: {sub_url}, resp: {json}");
37 Ok(json)
38 }
39 Err(err) => match err {
40 ureq::Error::Status(status, response) => {
41 let err_msg = response.into_json::<Json>().unwrap();
42 error!("<== ❌\n\tError api: {sub_url}, status: {status}, error: {err_msg}");
43 return Err(Error::ApiError(format!("{err_msg}")));
44 }
45 ureq::Error::Transport(e) => {
46 error!("<== ❌\n\tError api: {sub_url}, error: {:?}", e.to_string());
47 return Err(Error::RequestError(e.to_string()));
48 }
49 },
50 }
51}