1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
pub mod credits;
pub mod validate;

use crate::credits::ResponseSuccess as CreditsResponseSuccess;
use crate::validate::ResponseSuccess as ValidateResponseSuccess;
use reqwest::Client;
use serde::Deserialize;
use std::error::Error;
use std::fmt::Debug;
use std::net::IpAddr;

pub(crate) const API_URL: &str = "https://api.zerobounce.net/v2";

#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum ResponseType<T> {
    // When the API responds with success. The HTTP status is 200
    Success(Box<T>),
    // When the API responds with error. The HTTP status is 200
    Error(ResponseError),
}

#[derive(Debug, Deserialize)]
pub struct ResponseError {
    pub error: String,
}

pub struct Api {
    api_url: String,
    api_key: String,
    client: Client,
}

impl Api {
    pub fn new(api_key: impl Into<String>) -> Api {
        Api {
            api_url: API_URL.to_string(),
            api_key: api_key.into(),
            client: Client::new(),
        }
    }

    pub fn set_api_url(&mut self, api_url: impl Into<String>) -> &mut Self {
        self.api_url = api_url.into().trim_end_matches('/').to_string();
        self
    }

    pub fn get_api_url(&self) -> String {
        self.api_url.to_string()
    }

    pub fn set_api_key(&mut self, api_key: impl Into<String>) -> &mut Self {
        self.api_key = api_key.into();
        self
    }

    pub fn get_api_key(&self) -> String {
        self.api_key.to_string()
    }

    pub async fn validate(
        &self,
        email: impl Into<String>,
        ip_address: Option<IpAddr>,
    ) -> Result<ResponseType<ValidateResponseSuccess>, Box<dyn Error>> {
        let email_address = email.into();
        let mut url = format!(
            "{}/validate?api_key={}&email={}",
            self.api_url, self.api_key, email_address
        );
        if ip_address.is_some() {
            url = format!("{}&ip_address={}", url, ip_address.unwrap());
        }

        let response: ResponseType<ValidateResponseSuccess> = self
            .client
            .get(url)
            .send()
            .await?
            .json::<ResponseType<ValidateResponseSuccess>>()
            .await?;

        Ok(response)
    }

    pub async fn get_credits(
        &self,
    ) -> Result<ResponseType<CreditsResponseSuccess>, Box<dyn Error>> {
        let url: String = format!("{}/getcredits?api_key={}", self.api_url, self.api_key);

        let response: ResponseType<CreditsResponseSuccess> = self
            .client
            .get(url)
            .send()
            .await?
            .json::<ResponseType<CreditsResponseSuccess>>()
            .await?;

        Ok(response)
    }
}

#[cfg(test)]
mod tests {
    use crate::Api;

    #[test]
    fn api_url() {
        let check_api_url: &str = "https://example.com";

        let mut api: Api = Api::new("test");

        assert_eq!(crate::API_URL.to_string(), api.get_api_url());

        api.set_api_url(check_api_url);
        assert_eq!(check_api_url.to_string(), api.get_api_url());
    }

    #[test]
    fn api_key() {
        let mut api: Api = Api::new("test");

        assert_eq!("test".to_string(), api.get_api_key());

        api.set_api_key("test 2");
        assert_eq!("test 2".to_string(), api.get_api_key());
    }
}