From 095293e8e3fc0e31a97d8c6d9f7a06c9547112a8 Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Tue, 1 May 2018 21:37:37 +0200 Subject: 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. --- src/db.rs | 43 +++++++++++++++++++++++++++++++++++++++++++ src/models.rs | 7 +++++++ 2 files changed, 50 insertions(+) (limited to 'src') 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 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); + +impl Handler for DbExecutor { + type Result = ::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); diff --git a/src/models.rs b/src/models.rs index 5c7bbb12d36a..3ad4a5ed9d7d 100644 --- a/src/models.rs +++ b/src/models.rs @@ -88,6 +88,13 @@ pub struct NewThread { pub user_id: i32, } +#[derive(Deserialize, Insertable)] +#[table_name="users"] +pub struct NewUser { + pub email: String, + pub name: String, +} + #[derive(Deserialize, Insertable)] #[table_name="posts"] pub struct NewPost { -- cgit 1.4.1