about summary refs log tree commit diff
path: root/src/db.rs
diff options
context:
space:
mode:
authorVincent Ambo <tazjin@gmail.com>2018-05-01T19·37+0200
committerVincent Ambo <github@tazj.in>2018-05-01T22·33+0200
commit095293e8e3fc0e31a97d8c6d9f7a06c9547112a8 (patch)
tree1be5ca55e1b5cbdb49e76134d48467c741a9a1f7 /src/db.rs
parent1e57b879fbb1e76ba108846bd4fcb34472900f4f (diff)
feat(db): Add LookupOrCreateUser message
Adds a message to look up a user in the database based on their email
address. If the user does not exist, it is created.
Diffstat (limited to 'src/db.rs')
-rw-r--r--src/db.rs43
1 files changed, 43 insertions, 0 deletions
diff --git a/src/db.rs b/src/db.rs
index a04b3382447a..bfbdd193c4c7 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -52,6 +52,49 @@ impl Handler<ListThreads> for DbExecutor {
     }
 }
 
+/// Message used to look up a user based on their email-address. If
+/// the user does not exist, it is created.
+pub struct LookupOrCreateUser {
+    pub email: String,
+    pub name: String,
+}
+
+message!(LookupOrCreateUser, Result<User>);
+
+impl Handler<LookupOrCreateUser> for DbExecutor {
+    type Result = <LookupOrCreateUser as Message>::Result;
+
+    fn handle(&mut self,
+              msg: LookupOrCreateUser,
+              _: &mut Self::Context) -> Self::Result {
+        use schema::users;
+        use schema::users::dsl::*;
+
+        let conn = self.0.get()?;
+
+        let opt_user = users
+            .filter(email.eq(&msg.email))
+            .first(&conn).optional()?;
+
+        if let Some(user) = opt_user {
+            Ok(user)
+        } else {
+            let new_user = NewUser {
+                email: msg.email,
+                name: msg.name,
+            };
+
+            let user: User = diesel::insert_into(users::table)
+                .values(&new_user)
+                .get_result(&conn)?;
+
+            info!("Created new user {} with ID {}", new_user.email, user.id);
+
+            Ok(user)
+        }
+    }
+}
+
 /// Message used to fetch a specific thread. Returns the thread and
 /// its posts.
 pub struct GetThread(pub i32);