aboutsummaryrefslogblamecommitdiffstats
path: root/src/models/user.rs
blob: 5b92f6dce7246585820fa987d4c3874ab1103bdb (plain) (tree)
1
2
3
4
5
6




                       
                                                                           










                                        
                         







                                                                          


                                      

     





                                                                                 
                                                                                 
                                    




                                  
use diesel;
use diesel::prelude::*;
use schema::users;
use utils;

#[derive(AsChangeset, Clone, FromForm, Identifiable, Serialize, Queryable)]
pub struct User {
    pub id: i32,
    pub username: String,
    pub realname: Option<String>,
    pub email: Option<String>,
    pub password: String
}

#[derive(Default, FromForm, Insertable)]
#[table_name="users"]
pub struct NewUser {
    pub username: String,
    pub realname: Option<String>,
    pub email: Option<String>,
    pub password: String,
}

impl User {
    pub fn by_id(user_id: i32, conn: utils::DbConn) -> QueryResult<User> {
        use schema::users::dsl::*;
        users.filter(id.eq(user_id))
            .load::<User>(&*conn)
            .map(|ref v| v[0].clone())
    }

    pub fn by_email(user_email: &str, conn: utils::DbConn) -> QueryResult<User> {
        use schema::users::dsl::*;
        users.filter(email.eq(user_email))
            .get_result::<User>(&*conn)
    }

    pub fn create(new_user: &NewUser, conn: utils::DbConn) -> QueryResult<User> {
        use ::schema::users::dsl::*;
        diesel::insert_into(users)
            .values(new_user)
            .get_result(&*conn)
    }
}