File tree Expand file tree Collapse file tree 2 files changed +21
-11
lines changed Expand file tree Collapse file tree 2 files changed +21
-11
lines changed Original file line number Diff line number Diff line change 1
1
use chrono:: NaiveDateTime ;
2
+ use diesel:: { OptionalExtension , QueryResult } ;
3
+ use diesel_async:: { AsyncPgConnection , RunQueryDsl } ;
2
4
use secrecy:: SecretString ;
3
5
4
6
use crate :: models:: User ;
@@ -23,3 +25,21 @@ pub struct NewEmail<'a> {
23
25
pub email : & ' a str ,
24
26
pub verified : bool ,
25
27
}
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
+ }
Original file line number Diff line number Diff line change @@ -2,7 +2,6 @@ use chrono::NaiveDateTime;
2
2
use diesel:: prelude:: * ;
3
3
use diesel_async:: scoped_futures:: ScopedFutureExt ;
4
4
use diesel_async:: { AsyncConnection , AsyncPgConnection , RunQueryDsl } ;
5
- use secrecy:: SecretString ;
6
5
7
6
use crate :: app:: App ;
8
7
use crate :: controllers:: user:: update:: UserConfirmEmail ;
@@ -177,16 +176,7 @@ impl<'a> NewUser<'a> {
177
176
verified : false ,
178
177
} ;
179
178
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 ? {
190
180
// Swallows any error. Some users might insert an invalid email address here.
191
181
let email = UserConfirmEmail {
192
182
user_name : & user. gh_login ,
You can’t perform that action at this time.
0 commit comments