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
use reqwest::{Response, StatusCode};
use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::errors::PostmarkClientError;
use crate::types::APIError;
use crate::{errors, Result};
const POSTMARK_API_URL_BASE: &str = "https://api.postmarkapp.com";
const POSTMARK_TOKEN_HEADER: &str = "X-Postmark-Server-Token";
pub struct Client {
http_client: reqwest::Client,
token: String,
}
impl Client {
pub fn new(token: String) -> Client {
Client {
http_client: reqwest::Client::new(),
token,
}
}
pub fn new_with_client(token: String, http_client: reqwest::Client) -> Client {
Client { http_client, token }
}
async fn extract_error(response: Response) -> errors::PostmarkClientError {
let status = response.status();
match status {
StatusCode::UNAUTHORIZED => PostmarkClientError::Unauthorized,
StatusCode::NOT_FOUND => PostmarkClientError::RequestToLarge,
StatusCode::UNPROCESSABLE_ENTITY => {
let data = response.json::<APIError>().await;
match data {
Err(e) => PostmarkClientError::Reqwest(e),
Ok(e) => PostmarkClientError::UnprocessableEntity(e),
}
}
StatusCode::TOO_MANY_REQUESTS => PostmarkClientError::RateLimitExceeded,
StatusCode::INTERNAL_SERVER_ERROR => PostmarkClientError::InternalServerError,
StatusCode::SERVICE_UNAVAILABLE => PostmarkClientError::ServiceUnavailable,
_ => PostmarkClientError::UnknownPostmarkStatus(status),
}
}
pub(crate) async fn post<B, R>(&self, path: &str, body: &B) -> Result<R>
where
B: Serialize + ?Sized,
R: DeserializeOwned,
{
let response = self
.http_client
.post(format!("{:}{:}", POSTMARK_API_URL_BASE, path))
.header(POSTMARK_TOKEN_HEADER, &self.token)
.json(body)
.send()
.await?;
if !response.status().is_success() {
return Err(Client::extract_error(response).await);
}
Ok(response.json::<R>().await?)
}
}