cargo fmt

Signed-off-by: ATechnoHazard <amolele@gmail.com>
This commit is contained in:
Amogh Lele 2020-06-26 16:44:07 +05:30
parent 1aa0c5c278
commit 62df3f239a
No known key found for this signature in database
GPG Key ID: F475143EDEDEBA3C
24 changed files with 147 additions and 114 deletions

View File

@ -1,34 +1,47 @@
use rocket::Rocket;
use rocket::response::status;
use rocket::http::Status; use rocket::http::Status;
use rocket::response::status;
use rocket::Rocket;
use rocket_contrib::json::Json; use rocket_contrib::json::Json;
use serde_json::Value; use serde_json::Value;
#[catch(404)] #[catch(404)]
fn not_found() -> status::Custom<Json<Value>> { fn not_found() -> status::Custom<Json<Value>> {
status::Custom(Status::NotFound, Json(json!({ status::Custom(
Status::NotFound,
Json(json!({
"err":"route not found", "err":"route not found",
"msg": "The given route does not exist" "msg": "The given route does not exist"
}))) })),
)
} }
#[catch(422)] #[catch(422)]
fn unprocessable_entity() -> status::Custom<Json<Value>> { fn unprocessable_entity() -> status::Custom<Json<Value>> {
status::Custom(Status::UnprocessableEntity, Json(json!({ status::Custom(
Status::UnprocessableEntity,
Json(json!({
"err":"failed to process entity", "err":"failed to process entity",
"msg": "The given object could not be processed. This could be due to sending \ "msg": "The given object could not be processed. This could be due to sending \
malformed or incomplete JSON objects in the request body." malformed or incomplete JSON objects in the request body."
}))) })),
)
} }
#[catch(500)] #[catch(500)]
fn internal_server_error() -> status::Custom<Json<Value>> { fn internal_server_error() -> status::Custom<Json<Value>> {
status::Custom(Status::NotFound, Json(json!({ status::Custom(
Status::NotFound,
Json(json!({
"err":"internal server error", "err":"internal server error",
"msg": "Something went wrong, try again" "msg": "Something went wrong, try again"
}))) })),
)
} }
pub fn fuel(rocket: Rocket) -> Rocket { pub fn fuel(rocket: Rocket) -> Rocket {
rocket.register(catchers![not_found, unprocessable_entity, internal_server_error]) rocket.register(catchers![
not_found,
unprocessable_entity,
internal_server_error
])
} }

View File

@ -1,9 +1,9 @@
use diesel::PgConnection;
use diesel::r2d2::{PooledConnection, ConnectionManager};
use rocket::{Request, request, State, Outcome};
use rocket::request::FromRequest;
use rocket::http::Status;
use crate::utils::db::Pool; use crate::utils::db::Pool;
use diesel::r2d2::{ConnectionManager, PooledConnection};
use diesel::PgConnection;
use rocket::http::Status;
use rocket::request::FromRequest;
use rocket::{request, Outcome, Request, State};
use std::ops::Deref; use std::ops::Deref;
pub struct DbConn(pub PooledConnection<ConnectionManager<PgConnection>>); pub struct DbConn(pub PooledConnection<ConnectionManager<PgConnection>>);

View File

@ -0,0 +1 @@

View File

@ -1,5 +1,5 @@
pub mod routes;
pub mod catchers; pub mod catchers;
pub mod routes;
mod guards; mod guards;
mod misc; mod misc;

View File

@ -1,8 +1,9 @@
use rocket::{Rocket}; use rocket::Rocket;
#[get("/")] #[get("/")]
fn check() -> &'static str { "OK" } fn check() -> &'static str {
"OK"
}
pub fn fuel(rocket: Rocket) -> Rocket { pub fn fuel(rocket: Rocket) -> Rocket {
rocket.mount("/api/health", routes![check]) rocket.mount("/api/health", routes![check])

View File

@ -10,4 +10,3 @@ pub fn fuel(rocket: Rocket) -> Rocket {
rocket = paste::fuel(rocket); rocket = paste::fuel(rocket);
rocket rocket
} }

View File

@ -1,14 +1,18 @@
use std::ops::DerefMut; use std::ops::DerefMut;
use rocket::{http::{Cookie, Cookies, Status}, response::status, Rocket};
use rocket::response::status::Custom; use rocket::response::status::Custom;
use rocket::{
http::{Cookie, Cookies, Status},
response::status,
Rocket,
};
use rocket_contrib::json::Json; use rocket_contrib::json::Json;
use serde_json::Value; use serde_json::Value;
use crate::core::paste::{entity::Paste, service::create_paste, service::fetch_paste};
use crate::core::users::{service::create_or_fetch_user};
use crate::utils::phonetic_key;
use crate::api::guards::db; use crate::api::guards::db;
use crate::core::paste::{entity::Paste, service::create_paste, service::fetch_paste};
use crate::core::users::service::create_or_fetch_user;
use crate::utils::phonetic_key;
use diesel::result::Error; use diesel::result::Error;
@ -27,10 +31,15 @@ fn create(mut paste: Json<Paste>, conn: db::DbConn, mut ck: Cookies) -> Custom<J
// Create or fetch already existing user // Create or fetch already existing user
let user = match create_or_fetch_user(user_id, &conn) { let user = match create_or_fetch_user(user_id, &conn) {
Ok(user) => user, Ok(user) => user,
Err(e) => return status::Custom(Status::InternalServerError, Json(json!({ Err(e) => {
return status::Custom(
Status::InternalServerError,
Json(json!({
"err": e.to_string(), "err": e.to_string(),
"msg": "Failed to create or fetch user" "msg": "Failed to create or fetch user"
}))) })),
)
}
}; };
let new_paste = paste.deref_mut(); let new_paste = paste.deref_mut();
@ -41,18 +50,20 @@ fn create(mut paste: Json<Paste>, conn: db::DbConn, mut ck: Cookies) -> Custom<J
new_paste.belongs_to = Some(user.id); new_paste.belongs_to = Some(user.id);
match create_paste(new_paste, &conn) { match create_paste(new_paste, &conn) {
Ok(_) => { Ok(_) => status::Custom(
status::Custom(Status::Created, Json(json!({ Status::Created,
Json(json!({
"msg": "Successfully created paste", "msg": "Successfully created paste",
"paste_id": new_paste.id "paste_id": new_paste.id
}))) })),
} ),
Err(e) => { Err(e) => status::Custom(
status::Custom(Status::InternalServerError, Json(json!({ Status::InternalServerError,
Json(json!({
"err": e.to_string(), "err": e.to_string(),
"msg": "Failed to create paste" "msg": "Failed to create paste"
}))) })),
} ),
} }
} }
@ -62,14 +73,20 @@ fn fetch(id: String, conn: db::DbConn) -> Custom<Json<Value>> {
Ok(paste) => paste, Ok(paste) => paste,
Err(err) => { Err(err) => {
return match err.downcast_ref::<Error>() { return match err.downcast_ref::<Error>() {
Some(Error::NotFound) => Custom(Status::NotFound, Json(json!({ Some(Error::NotFound) => Custom(
Status::NotFound,
Json(json!({
"err": err.to_string(), "err": err.to_string(),
"msg": "Unable to find a paste with that ID" "msg": "Unable to find a paste with that ID"
}))), })),
_ => Custom(Status::InternalServerError, Json(json!({ ),
_ => Custom(
Status::InternalServerError,
Json(json!({
"err": err.to_string(), "err": err.to_string(),
"msg": "Something went wrong, try again" "msg": "Something went wrong, try again"
}))) })),
),
} }
} }
}; };

View File

@ -0,0 +1 @@

View File

@ -1,3 +1,3 @@
pub mod postgres;
pub mod entity; pub mod entity;
pub mod postgres;
pub mod service; pub mod service;

View File

@ -1,6 +1,6 @@
use diesel::prelude::*;
use diesel::pg::PgConnection;
use anyhow::Result; use anyhow::Result;
use diesel::pg::PgConnection;
use diesel::prelude::*;
use crate::core::users::entity::User; use crate::core::users::entity::User;
use crate::schema::users; use crate::schema::users;

View File

@ -1,5 +1,5 @@
use anyhow::Result; use anyhow::Result;
use bcrypt::{DEFAULT_COST, hash}; use bcrypt::{hash, DEFAULT_COST};
use diesel::pg::PgConnection; use diesel::pg::PgConnection;
use diesel::result::Error; use diesel::result::Error;
@ -16,8 +16,7 @@ pub fn create_user(user: &mut User, conn: &PgConnection) -> Result<usize> {
pub fn create_or_fetch_user(id: String, conn: &PgConnection) -> Result<User> { pub fn create_or_fetch_user(id: String, conn: &PgConnection) -> Result<User> {
let user = match postgres::find_user(id.clone(), conn) { let user = match postgres::find_user(id.clone(), conn) {
Ok(user) => user, Ok(user) => user,
Err(err) => { Err(err) => match err.downcast_ref::<Error>() {
match err.downcast_ref::<Error>() {
Some(Error::NotFound) => { Some(Error::NotFound) => {
let new_user = User { let new_user = User {
id: id.clone(), id: id.clone(),
@ -28,9 +27,8 @@ pub fn create_or_fetch_user(id: String, conn: &PgConnection) -> Result<User> {
postgres::create_user(&new_user, conn)?; postgres::create_user(&new_user, conn)?;
new_user new_user
} }
_ => return Err(err) _ => return Err(err),
} },
}
}; };
Ok(user) Ok(user)
} }

View File

@ -16,12 +16,12 @@ extern crate slog;
pub mod api; pub mod api;
pub mod core; pub mod core;
pub mod utils;
pub mod schema; pub mod schema;
pub mod utils;
use slog_term;
use slog_async;
use slog::{Drain, Logger}; use slog::{Drain, Logger};
use slog_async;
use slog_term;
embed_migrations!("migrations"); embed_migrations!("migrations");
@ -32,7 +32,6 @@ fn run_migrations(logger: &Logger) {
} }
} }
fn main() { fn main() {
dotenv::dotenv().ok(); dotenv::dotenv().ok();
@ -48,7 +47,5 @@ fn main() {
rocket = api::routes::fuel(rocket); rocket = api::routes::fuel(rocket);
rocket = api::catchers::fuel(rocket); rocket = api::catchers::fuel(rocket);
rocket.manage(utils::db::pool()) rocket.manage(utils::db::pool()).manage(logger).launch();
.manage(logger)
.launch();
} }

View File

@ -18,7 +18,4 @@ table! {
joinable!(pastes -> users (belongs_to)); joinable!(pastes -> users (belongs_to));
allow_tables_to_appear_in_same_query!( allow_tables_to_appear_in_same_query!(pastes, users,);
pastes,
users,
);

View File

@ -1,6 +1,6 @@
use diesel::pg::PgConnection; use diesel::pg::PgConnection;
use diesel::{r2d2, Connection};
use diesel::r2d2::ConnectionManager; use diesel::r2d2::ConnectionManager;
use diesel::{r2d2, Connection};
use std::env; use std::env;
pub type Pool = r2d2::Pool<ConnectionManager<PgConnection>>; pub type Pool = r2d2::Pool<ConnectionManager<PgConnection>>;

View File

@ -1,8 +1,13 @@
use rocket::{http::{Status, ContentType}, response::Responder, Request, response, Response, Outcome, State}; use rocket::{
http::{ContentType, Status},
response,
response::Responder,
Outcome, Request, Response, State,
};
use std::io::Cursor;
use slog::Logger;
use slog; use slog;
use slog::Logger;
use std::io::Cursor;
#[derive(Debug, Serialize, Clone)] #[derive(Debug, Serialize, Clone)]
pub enum ErrorCode { pub enum ErrorCode {
@ -32,14 +37,12 @@ impl Error {
Error { Error {
code, code,
msg: "".to_string(), msg: "".to_string(),
}.set_msg() }
.set_msg()
} }
pub fn custom(code: ErrorCode, msg: String) -> Error { pub fn custom(code: ErrorCode, msg: String) -> Error {
Error { Error { code, msg }
code,
msg,
}
} }
fn get_status_code(&self) -> Status { fn get_status_code(&self) -> Status {
@ -56,14 +59,16 @@ impl Error {
ErrorCode::NotAuthorized => Status::Forbidden, ErrorCode::NotAuthorized => Status::Forbidden,
ErrorCode::CorruptResource => Status::InternalServerError, ErrorCode::CorruptResource => Status::InternalServerError,
ErrorCode::LogicalConflict => Status::BadRequest, ErrorCode::LogicalConflict => Status::BadRequest,
ErrorCode::Unknown => Status::InternalServerError ErrorCode::Unknown => Status::InternalServerError,
} }
} }
fn set_msg(mut self) -> Self { fn set_msg(mut self) -> Self {
self.msg = match self.code.clone() { self.msg = match self.code.clone() {
ErrorCode::InvalidCredentials => "invalid credentials were provided".to_string(), ErrorCode::InvalidCredentials => "invalid credentials were provided".to_string(),
ErrorCode::MultipleAuthToken => "multiple authorization tokens were provided".to_string(), ErrorCode::MultipleAuthToken => {
"multiple authorization tokens were provided".to_string()
}
ErrorCode::NoAuthToken => "no authorization token was found".to_string(), ErrorCode::NoAuthToken => "no authorization token was found".to_string(),
ErrorCode::AuthTokenCreationFailed => "authorization token creation failed".to_string(), ErrorCode::AuthTokenCreationFailed => "authorization token creation failed".to_string(),
ErrorCode::MalformedAuthToken => "authorization token was malformed".to_string(), ErrorCode::MalformedAuthToken => "authorization token was malformed".to_string(),
@ -71,10 +76,14 @@ impl Error {
ErrorCode::ResourceAlreadyExists => "the given resource already exists".to_string(), ErrorCode::ResourceAlreadyExists => "the given resource already exists".to_string(),
ErrorCode::DatabaseError => "database error occured".to_string(), ErrorCode::DatabaseError => "database error occured".to_string(),
ErrorCode::InvalidData => "invalid data provided".to_string(), ErrorCode::InvalidData => "invalid data provided".to_string(),
ErrorCode::NotAuthorized => "you are not authorized to perform the requested operation".to_string(), ErrorCode::NotAuthorized => {
"you are not authorized to perform the requested operation".to_string()
}
ErrorCode::CorruptResource => "requested resource was corrupted".to_string(), ErrorCode::CorruptResource => "requested resource was corrupted".to_string(),
ErrorCode::LogicalConflict => "the request logically conflicts with the existing data".to_string(), ErrorCode::LogicalConflict => {
ErrorCode::Unknown => "unknown error occured".to_string() "the request logically conflicts with the existing data".to_string()
}
ErrorCode::Unknown => "unknown error occured".to_string(),
}; };
self self
} }

View File

@ -1,3 +1,3 @@
pub mod errors;
pub mod db; pub mod db;
pub mod errors;
pub mod phonetic_key; pub mod phonetic_key;