Skip to content

Commit 4d20df8

Browse files
committed
models/email: Extract NewEmail::insert_if_missing() fn
1 parent aa29653 commit 4d20df8

File tree

2 files changed

+21
-11
lines changed

2 files changed

+21
-11
lines changed

src/models/email.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
use chrono::NaiveDateTime;
2+
use diesel::{OptionalExtension, QueryResult};
3+
use diesel_async::{AsyncPgConnection, RunQueryDsl};
24
use secrecy::SecretString;
35

46
use crate::models::User;
@@ -23,3 +25,21 @@ pub struct NewEmail<'a> {
2325
pub email: &'a str,
2426
pub verified: bool,
2527
}
28+
29+
impl NewEmail<'_> {
30+
/// Inserts the email into the database and returns the confirmation token,
31+
/// or does nothing if it already exists and returns `None`.
32+
pub async fn insert_if_missing(
33+
&self,
34+
conn: &mut AsyncPgConnection,
35+
) -> QueryResult<Option<SecretString>> {
36+
diesel::insert_into(emails::table)
37+
.values(self)
38+
.on_conflict_do_nothing()
39+
.returning(emails::token)
40+
.get_result::<String>(conn)
41+
.await
42+
.map(Into::into)
43+
.optional()
44+
}
45+
}

src/models/user.rs

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ use chrono::NaiveDateTime;
22
use diesel::prelude::*;
33
use diesel_async::scoped_futures::ScopedFutureExt;
44
use diesel_async::{AsyncConnection, AsyncPgConnection, RunQueryDsl};
5-
use secrecy::SecretString;
65

76
use crate::app::App;
87
use crate::controllers::user::update::UserConfirmEmail;
@@ -177,16 +176,7 @@ impl<'a> NewUser<'a> {
177176
verified: false,
178177
};
179178

180-
let token = insert_into(emails::table)
181-
.values(&new_email)
182-
.on_conflict_do_nothing()
183-
.returning(emails::token)
184-
.get_result::<String>(conn)
185-
.await
186-
.optional()?
187-
.map(SecretString::from);
188-
189-
if let Some(token) = token {
179+
if let Some(token) = new_email.insert_if_missing(conn).await? {
190180
// Swallows any error. Some users might insert an invalid email address here.
191181
let email = UserConfirmEmail {
192182
user_name: &user.gh_login,

0 commit comments

Comments
 (0)