From b191626ad932f3dc99e1b1b58add1ed1676e3cbc Mon Sep 17 00:00:00 2001 From: Timo Ley Date: Mon, 10 Jan 2022 14:37:27 +0100 Subject: [PATCH] Code improvements --- src/cdn/error.rs | 9 +++------ src/ipfs/error.rs | 2 +- src/lib/ipheader.rs | 3 ++- src/v1/error.rs | 8 ++++---- src/v1/routes.rs | 18 +++++++++--------- src/v1/sql.rs | 18 +++++++++--------- 6 files changed, 28 insertions(+), 30 deletions(-) diff --git a/src/cdn/error.rs b/src/cdn/error.rs index 97d36f5..503d98c 100644 --- a/src/cdn/error.rs +++ b/src/cdn/error.rs @@ -12,9 +12,9 @@ use crate::ipfs::error::IPFSError; #[derive(Error, Debug)] pub enum CDNError { #[error("SQL error: {0}")] - SQL(#[from] sqlx::Error), + Sql(#[from] sqlx::Error), #[error("IPFS error: {0}")] - IPFS(#[from] IPFSError), + Ipfs(#[from] IPFSError), #[error("Decode error: {0}")] Decode(#[from] FromUtf8Error), #[error("Internal server error")] @@ -28,10 +28,7 @@ impl IntoResponse for CDNError { fn into_response(self) -> axum::http::Response { let status = match self { - CDNError::SQL(err) => match err { - sqlx::Error::RowNotFound => StatusCode::NOT_FOUND, - _ => StatusCode::INTERNAL_SERVER_ERROR, - }, + CDNError::Sql(sqlx::Error::RowNotFound) => StatusCode::NOT_FOUND, _ => StatusCode::INTERNAL_SERVER_ERROR, }; status.into_response() diff --git a/src/ipfs/error.rs b/src/ipfs/error.rs index 2f17a96..3880a4a 100644 --- a/src/ipfs/error.rs +++ b/src/ipfs/error.rs @@ -6,5 +6,5 @@ pub enum IPFSError { #[error("Reqwest error: {0}")] Reqwest(#[from] reqwest::Error), #[error("URL parse error: {0}")] - URL(#[from] ParseError), + Url(#[from] ParseError), } diff --git a/src/lib/ipheader.rs b/src/lib/ipheader.rs index af24c1d..94c796c 100644 --- a/src/lib/ipheader.rs +++ b/src/lib/ipheader.rs @@ -18,7 +18,8 @@ where let header = req .headers() .and_then(|headers| headers.get("x-forwarded-for")); - let header = header.ok_or(ExtractError::HeaderMissing("X-Forwarded-For".to_string()))?; + let header = + header.ok_or_else(|| ExtractError::HeaderMissing("X-Forwarded-For".to_string()))?; let mut value = header.to_str()?; let pos = value.chars().position(|r| r == ','); value = match pos { diff --git a/src/v1/error.rs b/src/v1/error.rs index 7c9de30..648a135 100644 --- a/src/v1/error.rs +++ b/src/v1/error.rs @@ -27,7 +27,7 @@ pub enum APIError { #[error("{0}")] Internal(String), #[error("IPFS error: {0}")] - IPFS(#[from] IPFSError), + Ipfs(#[from] IPFSError), } impl ErrorResponse { @@ -35,7 +35,7 @@ impl ErrorResponse { let reason = status.canonical_reason().unwrap_or_default(); Self { status, - error: message.unwrap_or(reason.to_string()), + error: message.unwrap_or_else(|| reason.to_string()), } } } @@ -58,9 +58,9 @@ impl IntoResponse for APIError { APIError::Internal(err) => { ErrorResponse::new(StatusCode::INTERNAL_SERVER_ERROR, Some(err)) } - APIError::IPFS(_) => ErrorResponse::new(StatusCode::INTERNAL_SERVER_ERROR, None), + APIError::Ipfs(_) => ErrorResponse::new(StatusCode::INTERNAL_SERVER_ERROR, None), }; - let status = res.status.clone(); + let status = res.status; (status, Json(res)).into_response() } } diff --git a/src/v1/routes.rs b/src/v1/routes.rs index 5d86efc..5af1c83 100644 --- a/src/v1/routes.rs +++ b/src/v1/routes.rs @@ -109,17 +109,17 @@ async fn upload( let ipfs = vars.ipfs_client()?; while let Some(field) = form.next_field().await? { - match field.name().ok_or(APIError::BadRequest( - "A multipart-form field is missing a name".to_string(), - ))? { + match field.name().ok_or_else(|| { + APIError::BadRequest("A multipart-form field is missing a name".to_string()) + })? { "token" => token = Some(field.text().await?), "category" => category = Some(field.text().await?), "file" | "file[]" => { let filename = field .file_name() - .ok_or(APIError::BadRequest( - "A file field has no filename".to_string(), - ))? + .ok_or_else(|| { + APIError::BadRequest("A file field has no filename".to_string()) + })? .to_string(); let file = ipfs.add(field.bytes().await?, filename).await?; files.push(file); @@ -128,11 +128,11 @@ async fn upload( } } - let token = token.ok_or(APIError::Unauthorized("Missing token".to_string()))?; - let category = category.ok_or(APIError::BadRequest("Missing category".to_string()))?; + let token = token.ok_or_else(|| APIError::Unauthorized("Missing token".to_string()))?; + let category = category.ok_or_else(|| APIError::BadRequest("Missing category".to_string()))?; let user = User::check_token(token, &db_pool) .await? - .ok_or(APIError::Forbidden("token not existing".to_string()))?; + .ok_or_else(|| APIError::Forbidden("token not existing".to_string()))?; let total = (user.dayuploads as isize) + (files.len() as isize); if total > 20 { diff --git a/src/v1/sql.rs b/src/v1/sql.rs index f9a4e52..e9c0c73 100644 --- a/src/v1/sql.rs +++ b/src/v1/sql.rs @@ -46,9 +46,9 @@ impl Meme { cdn: String, ) -> Result> { let q: Vec = sqlx::query("SELECT memes.id, user, filename, category, name, UNIX_TIMESTAMP(timestamp) AS ts, cid FROM memes, users WHERE memes.user = users.id AND (category LIKE ? AND name LIKE ? AND filename LIKE ?) ORDER BY memes.id") - .bind(params.category.unwrap_or(String::from("%"))) - .bind(format!("%{}%", params.user.unwrap_or(String::from("")))) - .bind(format!("%{}%", params.search.unwrap_or(String::from("")))) + .bind(params.category.unwrap_or_else(|| String::from("%"))) + .bind(format!("%{}%", params.user.unwrap_or_else(String::new))) + .bind(format!("%{}%", params.search.unwrap_or_else(String::new))) .map(|row: MySqlRow| Self::new(DBMeme { id: row.get("id"), filename: row.get("filename"), @@ -68,9 +68,9 @@ impl Meme { cdn: String, ) -> Result { let q: Meme = sqlx::query("SELECT memes.id, user, filename, category, name, UNIX_TIMESTAMP(timestamp) AS ts, cid FROM memes, users WHERE memes.user = users.id AND (category LIKE ? AND name LIKE ? AND filename LIKE ?) ORDER BY RAND() LIMIT 1") - .bind(params.category.unwrap_or(String::from("%"))) - .bind(format!("%{}%", params.user.unwrap_or(String::from("")))) - .bind(format!("%{}%", params.search.unwrap_or(String::from("")))) + .bind(params.category.unwrap_or_else(|| String::from("%"))) + .bind(format!("%{}%", params.user.unwrap_or_else(String::new))) + .bind(format!("%{}%", params.search.unwrap_or_else(String::new))) .map(|row: MySqlRow| Self::new(DBMeme { id: row.get("id"), filename: row.get("filename"), @@ -130,9 +130,9 @@ impl Category { impl User { pub async fn get(params: UserIDQuery, pool: &MySqlPool) -> Result { let q: User = sqlx::query("SELECT id, name, MD5(token) AS hash, uploads FROM (SELECT id, name, IFNULL(count.uploads, 0) AS uploads FROM users LEFT JOIN (SELECT user, COUNT(*) AS uploads FROM memes WHERE DATE(timestamp) = CURDATE() GROUP BY (user)) AS count ON users.id = count.user) AS users, token WHERE users.id = token.uid AND (users.id LIKE ? OR token LIKE ? OR name LIKE ?) UNION SELECT id, name, 0 AS hash, 0 AS uploads FROM users WHERE id = '000'") - .bind(params.id.unwrap_or(String::from(""))) - .bind(params.token.unwrap_or(String::from(""))) - .bind(params.name.unwrap_or(String::from(""))) + .bind(params.id.unwrap_or_else(String::new)) + .bind(params.token.unwrap_or_else(String::new)) + .bind(params.name.unwrap_or_else(String::new)) .map(|row: MySqlRow| Self { id: row.get("id"), name: row.get("name"),