cli_covid19/
lib.rs

1use chrono::DateTime;
2use colored::*;
3use prettytable::{cell, row, Table};
4use reqwest::blocking::{Client, Request};
5use reqwest::Method;
6use serde_json::{from_str as json_from_str, Value as JsonValue};
7
8fn get_covid19_api(country: String) -> Result<String, Box<dyn std::error::Error>> {
9    Ok(format!(
10        "https://covid19.mathdro.id/api/countries/{}",
11        country
12    ))
13}
14
15fn handle_fetch_request(
16    url: String,
17) -> Result<reqwest::blocking::Response, Box<dyn std::error::Error>> {
18    Ok(Client::new()
19        .execute(Request::new(Method::GET, url.parse().unwrap()))
20        .unwrap())
21}
22
23pub fn init(country: String) {
24    let response = handle_fetch_request(get_covid19_api(country).unwrap()).unwrap();
25    let response_json: JsonValue = json_from_str(&response.text().unwrap()).unwrap();
26    let response_map = response_json.as_object().unwrap().to_owned();
27
28    let mut table = Table::new();
29
30    table.add_row(row![
31        "Last Update",
32        DateTime::parse_from_rfc3339(response_map["lastUpdate"].as_str().unwrap()).unwrap()
33    ]);
34
35    table.add_row(row![
36        "Confirmed",
37        response_map["confirmed"].as_object().unwrap()["value"]
38            .as_i64()
39            .unwrap()
40            .to_string()
41            .yellow()
42    ]);
43
44    table.add_row(row![
45        "Recovered",
46        response_map["recovered"].as_object().unwrap()["value"]
47            .as_i64()
48            .unwrap()
49            .to_string()
50            .green()
51    ]);
52
53    table.add_row(row![
54        "Deaths",
55        response_map["deaths"].as_object().unwrap()["value"]
56            .as_i64()
57            .unwrap()
58            .to_string()
59            .red()
60    ]);
61
62    table.printstd();
63}