users: add shorthand for UserOpError

This commit is contained in:
Peter Cai 2020-02-20 20:04:12 +08:00
parent 2178b1f833
commit fd2fd263d1
No known key found for this signature in database
GPG Key ID: 71F5FB4E4F3FD54F
1 changed files with 10 additions and 4 deletions

View File

@ -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
}