Skip to content

Commit

Permalink
format code using rustfmt
Browse files Browse the repository at this point in the history
  • Loading branch information
indpurvesh committed Dec 28, 2024
1 parent 76008ba commit e876c57
Show file tree
Hide file tree
Showing 21 changed files with 424 additions and 365 deletions.
41 changes: 15 additions & 26 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use std::num::ParseIntError;
use crate::models::validation_error::{ErrorMessage, ErrorResponse};
use axum::extract::multipart::MultipartError;
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
use axum::extract::multipart::MultipartError;
use handlebars::{RenderError, TemplateError};
use lettre::address::AddressError;
use rust_i18n::t;
use serde::Serialize;
use std::num::ParseIntError;
use tracing::log::error;
use crate::models::validation_error::{ErrorMessage, ErrorResponse};

pub type Result<T> = core::result::Result<T, Error>;

Expand All @@ -27,7 +27,7 @@ pub enum Error {

NotFound(String),

Forbidden
Forbidden,
}

impl core::fmt::Display for Error {
Expand All @@ -52,7 +52,6 @@ impl From<jsonwebtoken::errors::Error> for Error {
}
}


impl From<MultipartError> for Error {
fn from(val: MultipartError) -> Self {
error!("there is an issue with multipart error: {val:?}");
Expand Down Expand Up @@ -94,7 +93,6 @@ impl From<RenderError> for Error {
}
}


impl From<TemplateError> for Error {
fn from(actual_error: TemplateError) -> Self {
error!("there is an issue while registering the handlebar template with avored: {actual_error:?}");
Expand All @@ -109,15 +107,13 @@ impl From<ParseIntError> for Error {
}
}


impl From<AddressError> for Error {
fn from(actual_error: AddressError) -> Self {
error!("there is an issue while parsing email address: {actual_error:?}");
Error::Generic("parse lettre address parsing error".to_string())
}
}


impl From<lettre::error::Error> for Error {
fn from(actual_error: lettre::error::Error) -> Self {
error!("there is an issue lettre error: {actual_error:?}");
Expand All @@ -127,8 +123,6 @@ impl From<lettre::error::Error> for Error {

impl IntoResponse for Error {
fn into_response(self) -> Response {


// Create a placeholder Axum response.
// let mut response = StatusCode::INTERNAL_SERVER_ERROR.into_response();
// let mut response = self {
Expand All @@ -138,50 +132,45 @@ impl IntoResponse for Error {
// response.extensions_mut().insert(response);

match self {
Error::BadRequest(str) => {
(StatusCode::BAD_REQUEST, str).into_response()
},
Error::BadRequest(str) => (StatusCode::BAD_REQUEST, str).into_response(),
Error::Authentication => {
let mut errors: Vec<ErrorMessage> = vec![];
let error_message = ErrorMessage {
key: String::from("email"),
message: String::from(t!("email_password_not_matched"))
message: String::from(t!("email_password_not_matched")),
};

errors.push(error_message);
let error_response = ErrorResponse {
status: false,
errors
errors,
};
(StatusCode::UNAUTHORIZED, error_response).into_response()
},
}
Error::Forbidden => {
let mut errors: Vec<ErrorMessage> = vec![];
let error_message = ErrorMessage {
key: String::from("email"),
message: String::from(t!("admin_user_forbidden"))
message: String::from(t!("admin_user_forbidden")),
};

errors.push(error_message);
let error_response = ErrorResponse {
status: false,
errors
errors,
};
(StatusCode::FORBIDDEN, error_response).into_response()
},
Error::NotFound(msg) => {
(StatusCode::NOT_FOUND, msg).into_response()
},
_ => (StatusCode::INTERNAL_SERVER_ERROR, "test 500").into_response()
}
Error::NotFound(msg) => (StatusCode::NOT_FOUND, msg).into_response(),
_ => (StatusCode::INTERNAL_SERVER_ERROR, "test 500").into_response(),
}
}
}
impl IntoResponse for ErrorResponse {
fn into_response(self) -> Response {

let validation_errors = match serde_json::to_string(&self) {
let validation_errors = match serde_json::to_string(&self) {
Ok(str) => str,
_ => "validation error 400.".to_string()
_ => "validation error 400.".to_string(),
};

(StatusCode::BAD_REQUEST, validation_errors).into_response()
Expand Down
26 changes: 11 additions & 15 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,30 +1,27 @@
extern crate core;
use crate::api::rest_api_routes::rest_api_routes;
use crate::{avored_state::AvoRedState, error::Result};
use axum::extract::DefaultBodyLimit;
use axum::Router;
use std::{fs::File, path::Path, sync::Arc};
use axum::extract::DefaultBodyLimit;
use tokio::net::TcpListener;
use tower_http::services::ServeDir;
use tracing::info;
use tracing_subscriber::{
filter, prelude::__tracing_subscriber_SubscriberExt, util::SubscriberInitExt, Layer,
};
use crate::{
avored_state::AvoRedState,
error::Result
};
use crate::api::rest_api_routes::rest_api_routes;

const PER_PAGE: i64 = 10;
mod models;
mod api;
mod avored_state;
mod error;
mod middleware;
mod models;
mod providers;
mod query;
mod repositories;
mod services;
pub mod responses;
mod avored_state;
mod error;
mod query;
mod services;

rust_i18n::i18n!("resources/locales");

Expand All @@ -37,8 +34,7 @@ async fn main() -> Result<()> {
let app = Router::new()
.merge(rest_api_routes(state.clone()))
.nest_service("/public", static_routing_service)
.layer(DefaultBodyLimit::max(104857600))
;
.layer(DefaultBodyLimit::max(104857600));

println!(r" _ ____ _ ");
println!(r" / \__ _____ | _ \ ___ __| |");
Expand All @@ -54,7 +50,7 @@ async fn main() -> Result<()> {
// let addr = SocketAddr::from(([127, 0, 0, 1], 8080));
let listener = TcpListener::bind("0.0.0.0:8081").await.unwrap();
info!("{:<12} - on {:?}\n", "LISTENING", listener.local_addr());
axum::serve(listener , app.into_make_service())
axum::serve(listener, app.into_make_service())
.await
.unwrap();
// endregion: --- Start Server
Expand Down Expand Up @@ -100,4 +96,4 @@ fn init_log() {
.init();

tracing::info!(target: "metrics::cool_stuff_count", value = 42);
}
}
38 changes: 17 additions & 21 deletions src/models/admin_user_model.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::error::{Error, Result};
use crate::models::role_model::RoleModel;
use serde::{Deserialize, Serialize};
use surrealdb::sql::{Datetime, Object, Value};
use utoipa::ToSchema;
use crate::models::role_model::RoleModel;

use super::{BaseModel, Pagination};

Expand Down Expand Up @@ -41,31 +41,27 @@ impl TryFrom<Object> for AdminUserModel {
let is_super_admin = val.get("is_super_admin").get_bool()?;

let roles = match val.get("roles") {
Some(val) => {

match val.clone() {
Value::Array(v) => {
let mut arr = Vec::new();
Some(val) => match val.clone() {
Value::Array(v) => {
let mut arr = Vec::new();

for array in v.into_iter() {
let object = match array.clone() {
Value::Object(v) => v,
_ => surrealdb::sql::Object::default(),
};
for array in v.into_iter() {
let object = match array.clone() {
Value::Object(v) => v,
_ => surrealdb::sql::Object::default(),
};

let role_model: RoleModel = object.try_into()?;
let role_model: RoleModel = object.try_into()?;

arr.push(role_model)
}
arr
arr.push(role_model)
}
_ => Vec::new(),
arr
}
}
_ => Vec::new(),
},
None => Vec::new(),
};


let created_at = val.get("created_at").get_datetime()?;
let updated_at = val.get("updated_at").get_datetime()?;
let created_by = val.get("created_by").get_string()?;
Expand All @@ -82,7 +78,7 @@ impl TryFrom<Object> for AdminUserModel {
updated_at,
created_by,
updated_by,
roles
roles,
})
}
}
Expand All @@ -95,7 +91,7 @@ pub struct CreatableAdminUserModel {
pub profile_image: String,
pub is_super_admin: bool,
pub logged_in_username: String,
pub role_ids: Vec<String>
pub role_ids: Vec<String>,
}

#[derive(Serialize, Debug, Deserialize, Clone)]
Expand All @@ -105,7 +101,7 @@ pub struct UpdatableAdminUserModel {
pub profile_image: String,
pub is_super_admin: bool,
pub logged_in_username: String,
pub role_ids: Vec<String>
pub role_ids: Vec<String>,
}

#[derive(Serialize, Debug, Deserialize, Clone, Default)]
Expand Down
Loading

0 comments on commit e876c57

Please sign in to comment.