-
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.
- Loading branch information
1 parent
a358171
commit 03c8a6c
Showing
9 changed files
with
241 additions
and
3 deletions.
There are no files selected for viewing
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
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,99 @@ | ||
use super::error_chain_fmt; | ||
use crate::{EmailClient, SubscriberEmail}; | ||
use actix_web::{http::StatusCode, web, HttpResponse, ResponseError}; | ||
use anyhow::Context; | ||
use serde::Deserialize; | ||
use sqlx::PgPool; | ||
use std::fmt; | ||
use tracing::instrument; | ||
|
||
#[derive(Deserialize)] | ||
pub struct BodyData { | ||
title: String, | ||
content: Content, | ||
} | ||
|
||
#[derive(Deserialize)] | ||
pub struct Content { | ||
html: String, | ||
text: String, | ||
} | ||
|
||
#[derive(thiserror::Error)] | ||
pub enum PublishError { | ||
#[error(transparent)] | ||
UnexpectedError(#[from] anyhow::Error), | ||
} | ||
|
||
impl fmt::Debug for PublishError { | ||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
error_chain_fmt(self, f) | ||
} | ||
} | ||
|
||
impl ResponseError for PublishError { | ||
fn status_code(&self) -> StatusCode { | ||
match self { | ||
Self::UnexpectedError(_) => StatusCode::INTERNAL_SERVER_ERROR, | ||
} | ||
} | ||
} | ||
|
||
/// # Errors | ||
/// | ||
/// Will return `Err` if the stored email address in invalid. | ||
pub async fn publish_newsletter( | ||
body: web::Json<BodyData>, | ||
pool: web::Data<PgPool>, | ||
email_client: web::Data<EmailClient>, | ||
) -> Result<HttpResponse, PublishError> { | ||
let subscribers = get_confirmed_subscribers(&pool).await?; | ||
for subscriber in subscribers { | ||
match subscriber { | ||
Ok(subscriber) => { | ||
email_client | ||
.send_email( | ||
&subscriber.email, | ||
&body.title, | ||
&body.content.html, | ||
&body.content.text, | ||
) | ||
.await | ||
.with_context(|| { | ||
format!("Failed to send newsletter issue ot {}", subscriber.email) | ||
})?; | ||
} | ||
Err(error) => { | ||
tracing::warn!(error.cause_chain = ?error, "Skipping a confirmed subscriber. Their Stored contact details are invalid"); | ||
} | ||
} | ||
} | ||
Ok(HttpResponse::Ok().finish()) | ||
} | ||
|
||
struct ConfirmedSubscriber { | ||
email: SubscriberEmail, | ||
} | ||
|
||
#[instrument(name = "Get confirmed subscribers", skip(pool))] | ||
async fn get_confirmed_subscribers( | ||
pool: &PgPool, | ||
) -> Result<Vec<Result<ConfirmedSubscriber, anyhow::Error>>, anyhow::Error> { | ||
let confirmed_subscribers = sqlx::query!( | ||
r#" | ||
SELECT email | ||
FROM subscriptions | ||
WHERE status = 'confirmed' | ||
"#, | ||
) | ||
.fetch_all(pool) | ||
.await? | ||
.into_iter() | ||
.map(|r| match SubscriberEmail::parse(r.email) { | ||
Ok(email) => Ok(ConfirmedSubscriber { email }), | ||
Err(error) => Err(anyhow::anyhow!(error)), | ||
}) | ||
.collect(); | ||
|
||
Ok(confirmed_subscribers) | ||
} |
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
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,4 +1,5 @@ | ||
mod health_check; | ||
mod helpers; | ||
mod newsletter; | ||
mod subscriptions; | ||
mod subscriptions_confirm; |
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,117 @@ | ||
use wiremock::matchers::{any, method, path}; | ||
use wiremock::{Mock, ResponseTemplate}; | ||
|
||
use crate::helpers::{spawn_app, ConfirmationLinks, TestApp}; | ||
|
||
#[tokio::test] | ||
async fn newsletters_are_not_delivered_to_unconfirmed_subscribers() { | ||
let app = spawn_app().await; | ||
create_unconfirmed_subscriber(&app).await; | ||
|
||
Mock::given(any()) | ||
.respond_with(ResponseTemplate::new(200)) | ||
.expect(0) | ||
.mount(&app.email_server) | ||
.await; | ||
|
||
let newsletter_request_body = serde_json::json!({ | ||
"title": "Newsletter title", | ||
"content": { | ||
"text": "Newsletter body as plain text", | ||
"html": "<p>Newsletter body as HTML</p>", | ||
} | ||
}); | ||
let response = app.post_newsletters(newsletter_request_body).await; | ||
|
||
assert_eq!(response.status().as_u16(), 200); | ||
} | ||
|
||
#[tokio::test] | ||
async fn newsletters_are_delivered_to_confirmed_subscribers() { | ||
let app = spawn_app().await; | ||
create_confirmed_subscriber(&app).await; | ||
|
||
Mock::given(path("/email")) | ||
.and(method("POST")) | ||
.respond_with(ResponseTemplate::new(200)) | ||
.expect(1) | ||
.mount(&app.email_server) | ||
.await; | ||
|
||
let newsletter_request_body = serde_json::json!({ | ||
"title": "Newsletter title", | ||
"content": { | ||
"text": "Newsletter body as plain text", | ||
"html": "<p>Newsletter body as HTML</p>", | ||
} | ||
}); | ||
let response = app.post_newsletters(newsletter_request_body).await; | ||
|
||
assert_eq!(response.status().as_u16(), 200); | ||
} | ||
|
||
#[tokio::test] | ||
async fn newsletters_returns_400_for_invalid_data() { | ||
let app = spawn_app().await; | ||
let test_cases = vec![ | ||
( | ||
serde_json::json!({ | ||
"content": { | ||
"text": "Newsletter body as plain text", | ||
"html": "<p>Newsletter body as HTML</p>", | ||
} | ||
}), | ||
"missing title", | ||
), | ||
( | ||
serde_json::json!({"title": "Newsletter!"}), | ||
"missing content", | ||
), | ||
]; | ||
|
||
for (invalid_body, error_message) in test_cases { | ||
let response = app.post_newsletters(invalid_body).await; | ||
|
||
assert_eq!( | ||
400, | ||
response.status().as_u16(), | ||
"The API did not fail with 400 Bad Request when the payload was {error_message}" | ||
); | ||
} | ||
} | ||
|
||
/// Use the public API of the application under test to create | ||
/// an unconfirmed subscriber. | ||
async fn create_unconfirmed_subscriber(app: &TestApp) -> ConfirmationLinks { | ||
let body = "name=le%20guin&email=ursula_le_guin%40gmail.com"; | ||
|
||
let _mock_guard = Mock::given(path("/email")) | ||
.and(method("POST")) | ||
.respond_with(ResponseTemplate::new(200)) | ||
.named("Create unconfirmed subscruber") | ||
.expect(1) | ||
.mount_as_scoped(&app.email_server) | ||
.await; | ||
app.post_subscriptions(body.into()) | ||
.await | ||
.error_for_status() | ||
.unwrap(); | ||
|
||
let email_request = &app | ||
.email_server | ||
.received_requests() | ||
.await | ||
.unwrap() | ||
.pop() | ||
.unwrap(); | ||
app.get_confirmation_links(&email_request) | ||
} | ||
|
||
async fn create_confirmed_subscriber(app: &TestApp) { | ||
let confirmation_link = create_unconfirmed_subscriber(app).await; | ||
reqwest::get(confirmation_link.html) | ||
.await | ||
.unwrap() | ||
.error_for_status() | ||
.unwrap(); | ||
} |