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

View file

@ -7,6 +7,12 @@ use serde::Deserialize;
#[derive(Debug)] #[derive(Debug)]
pub struct UserOpError(pub String); pub struct UserOpError(pub String);
impl UserOpError {
fn new(s: impl Into<String>) -> UserOpError {
UserOpError(s.into())
}
}
#[derive(Queryable, Debug)] #[derive(Queryable, Debug)]
pub struct User { pub struct User {
pub id: i32, pub id: i32,
@ -30,12 +36,12 @@ pub struct NewUser {
impl User { impl User {
pub fn create(db: &SqliteConnection, new_user: &NewUser) -> Result<(), UserOpError> { pub fn create(db: &SqliteConnection, new_user: &NewUser) -> Result<(), UserOpError> {
match Self::find_user_by_email(db, &new_user.email) { 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) Err(_) => diesel::insert_into(users::table)
.values(new_user) .values(new_user)
.execute(db) .execute(db)
.map(|_| ()) .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)) let mut results = users.filter(email.eq(user_email))
.limit(1) .limit(1)
.load::<User>(db) .load::<User>(db)
.map_err(|_| UserOpError("Database error".to_string()))?; .map_err(|_| UserOpError::new("Database error"))?;
if results.is_empty() { if results.is_empty() {
Result::Err(UserOpError("No matching user found".to_string())) Result::Err(UserOpError::new("No matching user found"))
} else { } else {
Result::Ok(results.remove(0)) // Take ownership, kill the stupid Vec Result::Ok(results.remove(0)) // Take ownership, kill the stupid Vec
} }