Skip to content

Commit 75bb053

Browse files
committed
models/email: Extract NewEmail::insert_or_update() fn
1 parent 63ed030 commit 75bb053

File tree

2 files changed

+18
-11
lines changed

2 files changed

+18
-11
lines changed

src/controllers/user/update.rs

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use crate::app::AppState;
22
use crate::auth::AuthCheck;
33
use crate::controllers::helpers::ok_true;
44
use crate::models::NewEmail;
5-
use crate::schema::{emails, users};
5+
use crate::schema::users;
66
use crate::util::errors::{bad_request, server_error, AppResult};
77
use axum::extract::Path;
88
use axum::response::Response;
@@ -99,16 +99,8 @@ pub async fn update_user(
9999
verified: false,
100100
};
101101

102-
let token = diesel::insert_into(emails::table)
103-
.values(&new_email)
104-
.on_conflict(emails::user_id)
105-
.do_update()
106-
.set(&new_email)
107-
.returning(emails::token)
108-
.get_result::<String>(&mut conn)
109-
.await
110-
.map(SecretString::from)
111-
.map_err(|_| server_error("Error in creating token"))?;
102+
let token = new_email.insert_or_update(&mut conn).await;
103+
let token = token.map_err(|_| server_error("Error in creating token"))?;
112104

113105
// This swallows any errors that occur while attempting to send the email. Some users have
114106
// an invalid email set in their GitHub profile, and we should let them sign in even though

src/models/email.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,19 @@ impl NewEmail<'_> {
5151
.map(Into::into)
5252
.optional()
5353
}
54+
55+
pub async fn insert_or_update(
56+
&self,
57+
conn: &mut AsyncPgConnection,
58+
) -> QueryResult<SecretString> {
59+
diesel::insert_into(emails::table)
60+
.values(self)
61+
.on_conflict(emails::user_id)
62+
.do_update()
63+
.set(self)
64+
.returning(emails::token)
65+
.get_result::<String>(conn)
66+
.await
67+
.map(Into::into)
68+
}
5469
}

0 commit comments

Comments
 (0)