-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: set up email client with Resend
- Loading branch information
1 parent
363579e
commit eddf433
Showing
10 changed files
with
516 additions
and
138 deletions.
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,3 +6,8 @@ database: | |
username: "postgres" | ||
password: "password" | ||
database_name: "newsletter" | ||
email_client: | ||
base_url: "localhost" | ||
sender_email: "[email protected]" | ||
authorization_token: "my-secret-token" | ||
timeout_milliseconds: 10000 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,3 +2,6 @@ application: | |
host: 0.0.0.0 | ||
database: | ||
require_ssl: true | ||
email_client: | ||
base_url: "https://api.resend.com" | ||
sender_email: "[email protected]" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,212 @@ | ||
use crate::domain::SubscriberEmail; | ||
use reqwest::Client; | ||
use secrecy::{ExposeSecret, Secret}; | ||
|
||
pub struct EmailClient { | ||
http_client: reqwest::Client, | ||
sender: SubscriberEmail, | ||
base_url: String, | ||
authorization_token: Secret<String>, | ||
} | ||
|
||
impl EmailClient { | ||
pub fn new( | ||
base_url: String, | ||
sender: SubscriberEmail, | ||
authorization_token: Secret<String>, | ||
timeout: std::time::Duration, | ||
) -> Self { | ||
let http_client = Client::builder().timeout(timeout).build().unwrap(); | ||
|
||
Self { | ||
http_client, | ||
sender, | ||
base_url, | ||
authorization_token, | ||
} | ||
} | ||
|
||
pub async fn send_email( | ||
&self, | ||
recipient: SubscriberEmail, | ||
subject: &str, | ||
html_content: &str, | ||
text_content: &str, | ||
) -> Result<(), reqwest::Error> { | ||
let url = format!("{}/emails", self.base_url); | ||
let request_body = SendEmailRequest { | ||
from: self.sender.as_ref(), | ||
to: recipient.as_ref(), | ||
subject, | ||
html: html_content, | ||
text: text_content, | ||
}; | ||
|
||
self.http_client | ||
.post(&url) | ||
.header( | ||
"Authorization", | ||
format!("Bearer {}", self.authorization_token.expose_secret()), | ||
) | ||
.json(&request_body) | ||
.send() | ||
.await? | ||
.error_for_status()?; | ||
|
||
Ok(()) | ||
} | ||
} | ||
|
||
#[derive(serde::Serialize)] | ||
struct SendEmailRequest<'a> { | ||
from: &'a str, | ||
to: &'a str, | ||
subject: &'a str, | ||
html: &'a str, | ||
text: &'a str, | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use crate::domain::SubscriberEmail; | ||
use crate::email_client::EmailClient; | ||
use claims::assert_err; | ||
use claims::assert_ok; | ||
use fake::faker::internet::en::SafeEmail; | ||
use fake::faker::lorem::en::{Paragraph, Sentence}; | ||
use fake::{Fake, Faker}; | ||
use secrecy::Secret; | ||
use wiremock::matchers::{any, header, header_exists, method, path}; | ||
use wiremock::{Mock, MockServer, Request, ResponseTemplate}; | ||
|
||
/// Generate a random email subject. | ||
fn subject() -> String { | ||
Sentence(1..2).fake() | ||
} | ||
|
||
/// Generate random email content. | ||
fn content() -> String { | ||
Paragraph(1..10).fake() | ||
} | ||
|
||
/// Generate a random subscriber email. | ||
fn email() -> SubscriberEmail { | ||
SubscriberEmail::parse(SafeEmail().fake()).unwrap() | ||
} | ||
|
||
/// Get a test instance of `EmailClient`. | ||
fn email_client(base_url: String) -> EmailClient { | ||
EmailClient::new( | ||
base_url, | ||
email(), | ||
Secret::new(Faker.fake()), | ||
std::time::Duration::from_millis(200), | ||
) | ||
} | ||
|
||
struct SendEmailBodyMatcher; | ||
|
||
impl wiremock::Match for SendEmailBodyMatcher { | ||
fn matches(&self, request: &Request) -> bool { | ||
let result: Result<serde_json::Value, _> = serde_json::from_slice(&request.body); | ||
if let Ok(body) = result { | ||
body.get("from").is_some() | ||
&& body.get("to").is_some() | ||
&& body.get("subject").is_some() | ||
&& body.get("html").is_some() | ||
&& body.get("text").is_some() | ||
} else { | ||
false | ||
} | ||
} | ||
} | ||
|
||
#[tokio::test] | ||
async fn send_email_sends_the_expected_request() { | ||
// Arrange | ||
let mock_server = MockServer::start().await; | ||
let email_client = email_client(mock_server.uri()); | ||
|
||
Mock::given(header_exists("Authorization")) | ||
.and(header("Content-Type", "application/json")) | ||
.and(path("/emails")) | ||
.and(method("POST")) | ||
.and(SendEmailBodyMatcher) | ||
.respond_with(ResponseTemplate::new(200)) | ||
.expect(1) | ||
.mount(&mock_server) | ||
.await; | ||
|
||
// Act | ||
let _ = email_client | ||
.send_email(email(), &subject(), &content(), &content()) | ||
.await; | ||
|
||
// Assert | ||
// Mock expectations are checked on drop. | ||
} | ||
|
||
#[tokio::test] | ||
async fn send_email_succeeds_if_the_server_returns_200() { | ||
// Arrange | ||
let mock_server = MockServer::start().await; | ||
let email_client = email_client(mock_server.uri()); | ||
|
||
Mock::given(any()) | ||
.respond_with(ResponseTemplate::new(200)) | ||
.expect(1) | ||
.mount(&mock_server) | ||
.await; | ||
|
||
// Act | ||
let outcome = email_client | ||
.send_email(email(), &subject(), &content(), &content()) | ||
.await; | ||
|
||
// Assert | ||
assert_ok!(outcome); | ||
} | ||
|
||
#[tokio::test] | ||
async fn send_email_fails_if_the_server_returns_500() { | ||
// Arrange | ||
let mock_server = MockServer::start().await; | ||
let email_client = email_client(mock_server.uri()); | ||
|
||
Mock::given(any()) | ||
.respond_with(ResponseTemplate::new(500)) | ||
.expect(1) | ||
.mount(&mock_server) | ||
.await; | ||
|
||
// Act | ||
let outcome = email_client | ||
.send_email(email(), &subject(), &content(), &content()) | ||
.await; | ||
|
||
// Assert | ||
assert_err!(outcome); | ||
} | ||
|
||
#[tokio::test] | ||
async fn send_email_times_out_if_the_server_takes_too_long() { | ||
// Arrange | ||
let mock_server = MockServer::start().await; | ||
let email_client = email_client(mock_server.uri()); | ||
|
||
let response = ResponseTemplate::new(200).set_delay(std::time::Duration::from_secs(180)); | ||
Mock::given(any()) | ||
.respond_with(response) | ||
.expect(1) | ||
.mount(&mock_server) | ||
.await; | ||
|
||
// Act | ||
let outcome = email_client | ||
.send_email(email(), &subject(), &content(), &content()) | ||
.await; | ||
|
||
// Assert | ||
assert_err!(outcome); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,6 @@ | ||
pub mod configuration; | ||
pub mod domain; | ||
pub mod email_client; | ||
pub mod routes; | ||
pub mod startup; | ||
pub mod telemetry; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters