users: add shorthand for UserOpError
This commit is contained in:
parent
2178b1f833
commit
fd2fd263d1
14
src/user.rs
14
src/user.rs
|
@ -7,6 +7,12 @@ use serde::Deserialize;
|
|||
#[derive(Debug)]
|
||||
pub struct UserOpError(pub String);
|
||||
|
||||
impl UserOpError {
|
||||
fn new(s: impl Into<String>) -> UserOpError {
|
||||
UserOpError(s.into())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Queryable, Debug)]
|
||||
pub struct User {
|
||||
pub id: i32,
|
||||
|
@ -30,12 +36,12 @@ pub struct NewUser {
|
|||
impl User {
|
||||
pub fn create(db: &SqliteConnection, new_user: &NewUser) -> Result<(), UserOpError> {
|
||||
match Self::find_user_by_email(db, &new_user.email) {
|
||||
Ok(_) => Err(UserOpError("User already registered".to_string())),
|
||||
Ok(_) => Err(UserOpError::new("User already registered")),
|
||||
Err(_) => diesel::insert_into(users::table)
|
||||
.values(new_user)
|
||||
.execute(db)
|
||||
.map(|_| ())
|
||||
.map_err(|_| UserOpError("Database error".to_string()))
|
||||
.map_err(|_| UserOpError::new("Database error"))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -43,9 +49,9 @@ impl User {
|
|||
let mut results = users.filter(email.eq(user_email))
|
||||
.limit(1)
|
||||
.load::<User>(db)
|
||||
.map_err(|_| UserOpError("Database error".to_string()))?;
|
||||
.map_err(|_| UserOpError::new("Database error"))?;
|
||||
if results.is_empty() {
|
||||
Result::Err(UserOpError("No matching user found".to_string()))
|
||||
Result::Err(UserOpError::new("No matching user found"))
|
||||
} else {
|
||||
Result::Ok(results.remove(0)) // Take ownership, kill the stupid Vec
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue