Skip to main content

nerva/clients/
apod.rs

1use crate::core::{Client, Params};
2use std::error::Error;
3
4/// Params for the APOD API
5#[derive(Clone, Copy, Debug, PartialEq)]
6pub enum ApodParams<'p>
7{
8    #[doc = "Date of the APOD image"]
9    Date(&'p str),
10    #[doc = "Start date of the interval"]
11    StartDate(&'p str),
12    #[doc = "End date of the interval"]
13    EndDate(&'p str),
14    #[doc = "Number of images to return"]
15    Count(usize),
16    #[doc = "Include thumbnail images in the response"]
17    Thumbs(bool),
18}
19
20impl<'p> Into<String> for ApodParams<'p>
21{
22    fn into(self) -> String
23    {
24        match self
25        {
26            ApodParams::Date(date) => format!("date={}", date),
27            ApodParams::StartDate(date) => format!("start_date={}", date),
28            ApodParams::EndDate(date) => format!("end_date={}", date),
29            ApodParams::Count(count) => format!("count={}", count),
30            ApodParams::Thumbs(thumbs) => format!("thumbs={}", thumbs),
31        }
32    }
33}
34
35impl<'p> Default for ApodParams<'p>
36{
37    fn default() -> Self
38    {
39        let date = "2020-01-01";
40        return ApodParams::Date(date);
41    }
42}
43
44impl<'p> Params for ApodParams<'p> {}
45
46/// APOD API client
47#[derive(Clone, Debug)]
48pub struct Apod {}
49
50impl Default for Apod
51{
52    fn default() -> Self { Self {} }
53}
54
55impl<'p, PARAMS> Client<PARAMS> for Apod
56where
57    PARAMS: Params,
58{
59    const BASE_URL: &'static str = "https://api.nasa.gov/planetary/apod";
60    type Response = serde_json::Value;
61
62    fn get(&self, params: PARAMS) -> Result<Self::Response, Box<dyn Error>>
63    {
64        let burl: &'static str = <Apod as Client<PARAMS>>::BASE_URL;
65        let url = format!("{}/?{}", burl, params.into());
66        let url_with_key = crate::prelude::keys::include(&url)?;
67        let response = ureq::get(&url_with_key).call()?;
68        let json = serde_json::json!(response.into_string()?);
69        Ok(json)
70    }
71}