cargo fmt
Signed-off-by: ATechnoHazard <amolele@gmail.com>
This commit is contained in:
parent
1aa0c5c278
commit
62df3f239a
@ -1,34 +1,47 @@
|
||||
use rocket::Rocket;
|
||||
use rocket::response::status;
|
||||
use rocket::http::Status;
|
||||
use rocket::response::status;
|
||||
use rocket::Rocket;
|
||||
use rocket_contrib::json::Json;
|
||||
use serde_json::Value;
|
||||
|
||||
#[catch(404)]
|
||||
fn not_found() -> status::Custom<Json<Value>> {
|
||||
status::Custom(Status::NotFound, Json(json!({
|
||||
"err":"route not found",
|
||||
"msg": "The given route does not exist"
|
||||
})))
|
||||
status::Custom(
|
||||
Status::NotFound,
|
||||
Json(json!({
|
||||
"err":"route not found",
|
||||
"msg": "The given route does not exist"
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
#[catch(422)]
|
||||
fn unprocessable_entity() -> status::Custom<Json<Value>> {
|
||||
status::Custom(Status::UnprocessableEntity, Json(json!({
|
||||
"err":"failed to process entity",
|
||||
"msg": "The given object could not be processed. This could be due to sending \
|
||||
malformed or incomplete JSON objects in the request body."
|
||||
})))
|
||||
status::Custom(
|
||||
Status::UnprocessableEntity,
|
||||
Json(json!({
|
||||
"err":"failed to process entity",
|
||||
"msg": "The given object could not be processed. This could be due to sending \
|
||||
malformed or incomplete JSON objects in the request body."
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
#[catch(500)]
|
||||
fn internal_server_error() -> status::Custom<Json<Value>> {
|
||||
status::Custom(Status::NotFound, Json(json!({
|
||||
"err":"internal server error",
|
||||
"msg": "Something went wrong, try again"
|
||||
})))
|
||||
status::Custom(
|
||||
Status::NotFound,
|
||||
Json(json!({
|
||||
"err":"internal server error",
|
||||
"msg": "Something went wrong, try again"
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
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
|
||||
])
|
||||
}
|
@ -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 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;
|
||||
|
||||
pub struct DbConn(pub PooledConnection<ConnectionManager<PgConnection>>);
|
||||
|
@ -0,0 +1 @@
|
||||
|
@ -1,5 +1,5 @@
|
||||
pub mod routes;
|
||||
pub mod catchers;
|
||||
pub mod routes;
|
||||
|
||||
mod guards;
|
||||
mod misc;
|
||||
|
@ -1,8 +1,9 @@
|
||||
use rocket::{Rocket};
|
||||
use rocket::Rocket;
|
||||
|
||||
#[get("/")]
|
||||
fn check() -> &'static str { "OK" }
|
||||
|
||||
fn check() -> &'static str {
|
||||
"OK"
|
||||
}
|
||||
|
||||
pub fn fuel(rocket: Rocket) -> Rocket {
|
||||
rocket.mount("/api/health", routes![check])
|
||||
|
@ -10,4 +10,3 @@ pub fn fuel(rocket: Rocket) -> Rocket {
|
||||
rocket = paste::fuel(rocket);
|
||||
rocket
|
||||
}
|
||||
|
||||
|
@ -1,14 +1,18 @@
|
||||
use std::ops::DerefMut;
|
||||
|
||||
use rocket::{http::{Cookie, Cookies, Status}, response::status, Rocket};
|
||||
use rocket::response::status::Custom;
|
||||
use rocket::{
|
||||
http::{Cookie, Cookies, Status},
|
||||
response::status,
|
||||
Rocket,
|
||||
};
|
||||
use rocket_contrib::json::Json;
|
||||
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::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;
|
||||
|
||||
@ -27,10 +31,15 @@ fn create(mut paste: Json<Paste>, conn: db::DbConn, mut ck: Cookies) -> Custom<J
|
||||
// Create or fetch already existing user
|
||||
let user = match create_or_fetch_user(user_id, &conn) {
|
||||
Ok(user) => user,
|
||||
Err(e) => return status::Custom(Status::InternalServerError, Json(json!({
|
||||
"err": e.to_string(),
|
||||
"msg": "Failed to create or fetch user"
|
||||
})))
|
||||
Err(e) => {
|
||||
return status::Custom(
|
||||
Status::InternalServerError,
|
||||
Json(json!({
|
||||
"err": e.to_string(),
|
||||
"msg": "Failed to create or fetch user"
|
||||
})),
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
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);
|
||||
|
||||
match create_paste(new_paste, &conn) {
|
||||
Ok(_) => {
|
||||
status::Custom(Status::Created, Json(json!({
|
||||
"msg": "Successfully created paste",
|
||||
"paste_id": new_paste.id
|
||||
})))
|
||||
}
|
||||
Err(e) => {
|
||||
status::Custom(Status::InternalServerError, Json(json!({
|
||||
Ok(_) => status::Custom(
|
||||
Status::Created,
|
||||
Json(json!({
|
||||
"msg": "Successfully created paste",
|
||||
"paste_id": new_paste.id
|
||||
})),
|
||||
),
|
||||
Err(e) => status::Custom(
|
||||
Status::InternalServerError,
|
||||
Json(json!({
|
||||
"err": e.to_string(),
|
||||
"msg": "Failed to create paste"
|
||||
})))
|
||||
}
|
||||
})),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@ -62,14 +73,20 @@ fn fetch(id: String, conn: db::DbConn) -> Custom<Json<Value>> {
|
||||
Ok(paste) => paste,
|
||||
Err(err) => {
|
||||
return match err.downcast_ref::<Error>() {
|
||||
Some(Error::NotFound) => Custom(Status::NotFound, Json(json!({
|
||||
"err": err.to_string(),
|
||||
"msg": "Unable to find a paste with that ID"
|
||||
}))),
|
||||
_ => Custom(Status::InternalServerError, Json(json!({
|
||||
"err": err.to_string(),
|
||||
"msg": "Something went wrong, try again"
|
||||
})))
|
||||
Some(Error::NotFound) => Custom(
|
||||
Status::NotFound,
|
||||
Json(json!({
|
||||
"err": err.to_string(),
|
||||
"msg": "Unable to find a paste with that ID"
|
||||
})),
|
||||
),
|
||||
_ => Custom(
|
||||
Status::InternalServerError,
|
||||
Json(json!({
|
||||
"err": err.to_string(),
|
||||
"msg": "Something went wrong, try again"
|
||||
})),
|
||||
),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
@ -0,0 +1 @@
|
||||
|
@ -1,3 +1,3 @@
|
||||
pub mod postgres;
|
||||
pub mod entity;
|
||||
pub mod postgres;
|
||||
pub mod service;
|
@ -1,6 +1,6 @@
|
||||
use diesel::prelude::*;
|
||||
use diesel::pg::PgConnection;
|
||||
use anyhow::Result;
|
||||
use diesel::pg::PgConnection;
|
||||
use diesel::prelude::*;
|
||||
|
||||
use crate::core::users::entity::User;
|
||||
use crate::schema::users;
|
||||
|
@ -1,5 +1,5 @@
|
||||
use anyhow::Result;
|
||||
use bcrypt::{DEFAULT_COST, hash};
|
||||
use bcrypt::{hash, DEFAULT_COST};
|
||||
use diesel::pg::PgConnection;
|
||||
use diesel::result::Error;
|
||||
|
||||
@ -16,21 +16,19 @@ pub fn create_user(user: &mut User, conn: &PgConnection) -> Result<usize> {
|
||||
pub fn create_or_fetch_user(id: String, conn: &PgConnection) -> Result<User> {
|
||||
let user = match postgres::find_user(id.clone(), conn) {
|
||||
Ok(user) => user,
|
||||
Err(err) => {
|
||||
match err.downcast_ref::<Error>() {
|
||||
Some(Error::NotFound) => {
|
||||
let new_user = User {
|
||||
id: id.clone(),
|
||||
username: None,
|
||||
password: None,
|
||||
activated: Some(false),
|
||||
};
|
||||
postgres::create_user(&new_user, conn)?;
|
||||
new_user
|
||||
}
|
||||
_ => return Err(err)
|
||||
Err(err) => match err.downcast_ref::<Error>() {
|
||||
Some(Error::NotFound) => {
|
||||
let new_user = User {
|
||||
id: id.clone(),
|
||||
username: None,
|
||||
password: None,
|
||||
activated: Some(false),
|
||||
};
|
||||
postgres::create_user(&new_user, conn)?;
|
||||
new_user
|
||||
}
|
||||
}
|
||||
_ => return Err(err),
|
||||
},
|
||||
};
|
||||
Ok(user)
|
||||
}
|
11
src/main.rs
11
src/main.rs
@ -16,12 +16,12 @@ extern crate slog;
|
||||
|
||||
pub mod api;
|
||||
pub mod core;
|
||||
pub mod utils;
|
||||
pub mod schema;
|
||||
pub mod utils;
|
||||
|
||||
use slog_term;
|
||||
use slog_async;
|
||||
use slog::{Drain, Logger};
|
||||
use slog_async;
|
||||
use slog_term;
|
||||
|
||||
embed_migrations!("migrations");
|
||||
|
||||
@ -32,7 +32,6 @@ fn run_migrations(logger: &Logger) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn main() {
|
||||
dotenv::dotenv().ok();
|
||||
|
||||
@ -48,7 +47,5 @@ fn main() {
|
||||
rocket = api::routes::fuel(rocket);
|
||||
rocket = api::catchers::fuel(rocket);
|
||||
|
||||
rocket.manage(utils::db::pool())
|
||||
.manage(logger)
|
||||
.launch();
|
||||
rocket.manage(utils::db::pool()).manage(logger).launch();
|
||||
}
|
||||
|
@ -18,7 +18,4 @@ table! {
|
||||
|
||||
joinable!(pastes -> users (belongs_to));
|
||||
|
||||
allow_tables_to_appear_in_same_query!(
|
||||
pastes,
|
||||
users,
|
||||
);
|
||||
allow_tables_to_appear_in_same_query!(pastes, users,);
|
||||
|
@ -1,6 +1,6 @@
|
||||
use diesel::pg::PgConnection;
|
||||
use diesel::{r2d2, Connection};
|
||||
use diesel::r2d2::ConnectionManager;
|
||||
use diesel::{r2d2, Connection};
|
||||
use std::env;
|
||||
|
||||
pub type Pool = r2d2::Pool<ConnectionManager<PgConnection>>;
|
||||
|
@ -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::Logger;
|
||||
use std::io::Cursor;
|
||||
|
||||
#[derive(Debug, Serialize, Clone)]
|
||||
pub enum ErrorCode {
|
||||
@ -32,14 +37,12 @@ impl Error {
|
||||
Error {
|
||||
code,
|
||||
msg: "".to_string(),
|
||||
}.set_msg()
|
||||
}
|
||||
.set_msg()
|
||||
}
|
||||
|
||||
pub fn custom(code: ErrorCode, msg: String) -> Error {
|
||||
Error {
|
||||
code,
|
||||
msg,
|
||||
}
|
||||
Error { code, msg }
|
||||
}
|
||||
|
||||
fn get_status_code(&self) -> Status {
|
||||
@ -56,14 +59,16 @@ impl Error {
|
||||
ErrorCode::NotAuthorized => Status::Forbidden,
|
||||
ErrorCode::CorruptResource => Status::InternalServerError,
|
||||
ErrorCode::LogicalConflict => Status::BadRequest,
|
||||
ErrorCode::Unknown => Status::InternalServerError
|
||||
ErrorCode::Unknown => Status::InternalServerError,
|
||||
}
|
||||
}
|
||||
|
||||
fn set_msg(mut self) -> Self {
|
||||
self.msg = match self.code.clone() {
|
||||
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::AuthTokenCreationFailed => "authorization token creation failed".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::DatabaseError => "database error occured".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::LogicalConflict => "the request logically conflicts with the existing data".to_string(),
|
||||
ErrorCode::Unknown => "unknown error occured".to_string()
|
||||
ErrorCode::LogicalConflict => {
|
||||
"the request logically conflicts with the existing data".to_string()
|
||||
}
|
||||
ErrorCode::Unknown => "unknown error occured".to_string(),
|
||||
};
|
||||
self
|
||||
}
|
||||
|
@ -1,3 +1,3 @@
|
||||
pub mod errors;
|
||||
pub mod db;
|
||||
pub mod errors;
|
||||
pub mod phonetic_key;
|
Loading…
Reference in New Issue
Block a user